import { z } from 'zod';
import { SyncDirectionSchema } from '../enums';

// =============================================================
// Sync — trigger / status
// =============================================================

export const TriggerSyncRequestSchema = z.object({
  hostId: z.string().uuid().optional().describe('Platform UUID; defaults to caller'),
});
export type TriggerSyncRequest = z.infer<typeof TriggerSyncRequestSchema>;

export const TriggerSyncResponseSchema = z.object({
  accepted: z.literal(true),
  syncLogId: z.string().uuid(),
  /// 入站记录数(从宿主拉到的)
  fetched: z.number().int(),
  /// 写入 patient_transactions 的条数(去重后)
  transactionsWritten: z.number().int(),
  /// 由 parser 衍生写入 patient_facts 的版本数
  factsEmitted: z.number().int(),
});
export type TriggerSyncResponse = z.infer<typeof TriggerSyncResponseSchema>;

/// 单患者即时 pull 响应(客服工作台"刷新数据"按钮)。
/// 返回 SyncLog id 供调用方轮询状态(若 run 时间较长)
export const RefreshPatientResponseSchema = z.object({
  syncLogId: z.string().uuid(),
  /// running / success / partial — failed 通过 BizError 抛出
  status: z.string(),
  /// true = 调用方请求被合并到正在进行中的 run(30s 内去重)
  dedupedFromExisting: z.boolean().optional(),
});
export type RefreshPatientResponse = z.infer<typeof RefreshPatientResponseSchema>;

/// SyncLog 视图(对外读出)
export const SyncLogViewSchema = z.object({
  id: z.string().uuid(),
  hostId: z.string().uuid(),
  tenantId: z.string(),
  patientId: z.string().uuid().nullable(),
  direction: SyncDirectionSchema,
  resource: z.string(),
  triggeredBy: z.string().nullable(),
  status: z.string(),
  cursorBefore: z.string().nullable(),
  cursorAfter: z.string().nullable(),
  fetched: z.number().int(),
  transactionsWritten: z.number().int(),
  factsEmitted: z.number().int(),
  duplicates: z.number().int().describe('幂等去重命中数'),
  failed: z.number().int(),
  errorMessage: z.string().nullable(),
  startedAt: z.string(),
  endedAt: z.string().nullable(),
});
export type SyncLogView = z.infer<typeof SyncLogViewSchema>;
