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(),
  /// W4 末:本次写入的 transaction / fact 条数(UI toast 显示)
  transactionsWritten: z.number().int().optional(),
  factsEmitted: z.number().int().optional(),
  /// W4 末:本次刷新后新生成 plan 数(<= 1,plan = patient 级触达单元)
  plansCreated: z.number().int().optional(),
  /// 本次重算对该患者 plan 的结果(前端据此提示/切版本):
  ///   created/superseded=有新版本(切到 currentPlanId)· closed=缺口已解决已关闭(提示+退出)
  ///   unchanged/suppressed/none=无需切换 · error=重算异常
  planOutcome: z
    .enum(['created', 'superseded', 'unchanged', 'suppressed', 'closed', 'none', 'error'])
    .optional(),
  /// 重算后该患者当前 active/assigned plan id(可能是新版本;关闭/无 plan 时 null)
  currentPlanId: z.string().uuid().nullable().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>;
