import { z } from 'zod';
import { FactKindSchema, FactStatusSchema } from '../enums';

// =============================================================
// Layer 1 — patient_transactions(操作账本入站)
// =============================================================

/// Push 路径的 transaction 入站请求 — 宿主推完整事件报文,adapter 验签后直接落库。
/// pull 路径不走此接口(adapter 内部合成 transaction)。
export const IngestTransactionInputSchema = z.object({
  /// 宿主原生事件 ID;**幂等键**,push 路径必填
  sourceEventId: z.string().min(1).describe('Host event ID; idempotency key'),
  /// 宿主侧 user id(可空,系统自动事件无 actor)
  sourceActorId: z.string().optional(),
  /// 操作角色(doctor/receptionist/staff/system,宿主自定义)
  sourceActorRole: z.string().optional(),
  /// 操作发生诊所(立柱业务字段)
  clinicId: z.string().min(1),
  /// 患者宿主侧 ID(可空 — 部分管理动作无 patient 主体)
  patientExternalId: z.string().optional(),
  /// 动作类型 — 应用层 zod enum 校验(见 TransactionAction)
  action: z.string().min(1),
  /// 被操作主体类型 — 应用层 zod enum 校验(见 SubjectType)
  subjectType: z.string().min(1),
  /// 宿主侧主体业务 ID(如 apt_001;同 subject_id 可被多次操作)
  subjectId: z.string().min(1),
  /// 宿主原生 payload(adapter 收到啥存啥,parser 用 fieldMapping 解析)
  rawPayload: z.record(z.string(), z.unknown()),
  /// 宿主侧实际发生时间(ISO 8601 带时区)
  occurredAt: z.string().describe('Host-side occurred time, ISO 8601 with offset'),
});
export type IngestTransactionInput = z.infer<typeof IngestTransactionInputSchema>;

export const IngestTransactionsRequestSchema = z.object({
  events: z.array(IngestTransactionInputSchema).min(1).max(500),
});
export type IngestTransactionsRequest = z.infer<typeof IngestTransactionsRequestSchema>;

export const IngestTransactionsResponseSchema = z.object({
  accepted: z.number().int(),
  written: z.number().int().describe('Newly written transactions (after idempotency dedup)'),
  duplicates: z.number().int().describe('source_event_id already existed, skipped'),
  factsEmitted: z.number().int().describe('Fact versions emitted by parser'),
  rejected: z.number().int(),
  errors: z.array(z.object({ index: z.number().int(), reason: z.string() })),
});
export type IngestTransactionsResponse = z.infer<typeof IngestTransactionsResponseSchema>;

// =============================================================
// Layer 1 — patient_facts(API 读出)
// =============================================================

/// 单条 fact 视图(对外展示用,客服工作台 / 时间轴消费)
export const PatientFactViewSchema = z.object({
  id: z.string().uuid(),
  subjectId: z.string(),
  kind: FactKindSchema,
  type: z.string(),
  status: FactStatusSchema,
  version: z.number().int(),
  clinicId: z.string().nullable(),
  occurredAt: z.string().nullable(),
  plannedFor: z.string().nullable(),
  validFrom: z.string().nullable(),
  validUntil: z.string().nullable(),
  title: z.string().nullable(),
  summary: z.string().nullable(),
  content: z.record(z.string(), z.unknown()),
  transactionIds: z.array(z.string().uuid()),
  createdAt: z.string(),
  updatedAt: z.string(),
  supersededAt: z.string().nullable(),
});
export type PatientFactView = z.infer<typeof PatientFactViewSchema>;

/// Patient timeline 响应 — 含 active facts 列表 + patient 基本信息
export const PatientTimelineResponseSchema = z.object({
  patient: z.object({
    id: z.string().uuid(),
    externalId: z.string(),
    name: z.string().nullable(),
    phone: z.string().nullable(),
    gender: z.string().nullable(),
    birthDate: z.string().nullable(),
    status: z.string(),
  }),
  facts: z.array(PatientFactViewSchema),
});
export type PatientTimelineResponse = z.infer<typeof PatientTimelineResponseSchema>;
