'use client';

import { api } from '@/lib/api-client';

// 后端 RecallDebugReport 的镜像类型(@pac/service 不对 web 导出,这里本地声明)。
export interface RecallDebugReport {
  patient: { id: string; externalId: string; name: string | null; active: boolean };
  recalled: {
    hasActivePlan: boolean;
    engineWouldRecall: boolean;
    plans: TracePlan[];
  };
  notRecalled: {
    compliance: { pass: boolean; active: boolean; doNotContact: boolean; deceased: boolean };
    signalCount: number;
    signals: SignalFunnel[];
  };
  groundTruth: { engineHitCount: number; hitSubKeys: string[] };
  note: string;
  computedAt: string;
}

export interface SignalFunnel {
  factId: string;
  code: string;
  codeName: string;
  subKey: string | null;
  engineConfirmed: boolean;
  type: string;
  occurredAt: string | null;
  daysSince: number | null;
  gates: {
    cooldown: { pass: boolean; detail: string };
    alreadyTreated: {
      pass: boolean;
      detail: string;
      evidence: { factId: string; category: string; occurredAt: string | null }[];
    };
    futureAppointment: {
      pass: boolean;
      evidence: { factId: string; plannedFor: string | null } | null;
    };
  };
  verdict: 'would_recall' | 'blocked' | 'blocked_compliance';
  blockingGate: string | null;
}

export interface TracePlan {
  planId: string;
  version: number;
  status: string;
  isActive: boolean;
  priorityScore: number;
  generatedAt: string;
  reasons: TraceReason[];
}

export interface PatientCandidate {
  id: string;
  externalId: string;
  name: string | null;
  gender: string | null;
  age: number | null;
  medicalRecordNumber: string | null;
  active: boolean;
}

export interface TraceReason {
  scenario: string;
  subKey: string | null;
  priorityScore: number;
  reason: string;
  breakdown: unknown;
  signals: unknown;
  evidence: TraceEvidenceFact[];
}

export interface TraceEvidenceFact {
  factId: string;
  type: string | null;
  status: string | null;
  version: number | null;
  code: string | null;
  doctor: string | null;
  occurredAt: string | null;
  transactions: {
    transactionId: string;
    sourceEventId: string | null;
    subjectType: string | null;
    occurredAt: string | null;
  }[];
}

export interface TransactionRaw {
  id: string;
  sourceEventId: string | null;
  subjectType: string | null;
  occurredAt: string | null;
  rawPayload: unknown;
}

export const recallDebugApi = {
  explain: (patientId: string) =>
    api.get<RecallDebugReport>(
      `/pac/v1/admin/recall-debug/${encodeURIComponent(patientId)}`,
    ),
  rawPayload: (txId: string) =>
    api.get<TransactionRaw>(
      `/pac/v1/admin/recall-debug/transaction/${encodeURIComponent(txId)}/raw`,
    ),
  search: (q: string) =>
    api.get<PatientCandidate[]>(
      `/pac/v1/admin/recall-debug/search?q=${encodeURIComponent(q)}`,
    ),
};
