import { get, post, proj, upload } from "./http";
import type { VerificationRun } from "./types";
import type {
  RunDetail,
  SamplePreview,
  StatusCode,
  VerificationPlan,
  VerificationSubject,
} from "./types-extra";

/** Verification — master plan G.11, §23. Subjects are never returned to TP roles (server-enforced). */
export const listPlans = () => get<VerificationPlan[]>(proj("/verification/plans"));
export const savePlan = (plan: Partial<VerificationPlan> & { indicatorCode: string }) =>
  post<VerificationPlan>(proj("/verification/plans"), plan);
export const getSamplePreview = (q: { indicator: string; providerId: string; stage?: string }) =>
  get<SamplePreview>(proj("/verification/sample-preview"), q);
export const listStages = () =>
  get<{ indicatorCode: string; stageKey: string; label: string }[]>(proj("/verification/stages"));
export const createRun = (body: {
  indicator: string;
  providerId: string;
  period: string;
  stage?: string;
  seed?: string;
  preReport?: boolean;
}) => post<{ runId: string; jobId: string }>(proj("/verification/runs"), body);
export const getRun = (id: string) => get<RunDetail>(proj(`/verification/runs/${id}`));
export const listSubjects = (
  runId: string,
  q: { status?: string; role?: string; enumerator?: string } = {},
) => get<VerificationSubject[]>(proj(`/verification/runs/${runId}/subjects`), q);
export const assignSubjects = (runId: string, subjectIds: string[], enumerator: string) =>
  post<{ assigned: number }>(proj(`/verification/runs/${runId}/assign`), {
    subjectIds,
    enumerator,
  });
export const listEnumerators = () =>
  get<{ id: string; name: string }[]>(proj("/verification/enumerators"));
export const myWork = () => get<VerificationSubject[]>(proj("/verification/my-work"));
export const getSubject = (id: string) =>
  get<VerificationSubject>(proj(`/verification/subjects/${id}`));
export const markUnreachable = (id: string, note?: string) =>
  post<VerificationSubject>(proj(`/verification/subjects/${id}/unreachable`), note ? { note } : {});
export const saveResponse = (id: string, answers: Record<string, string>) =>
  post<VerificationSubject>(proj(`/verification/subjects/${id}/response`), { answers });
export const replaceSubject = (id: string) =>
  post<VerificationSubject>(proj(`/verification/subjects/${id}/replace`));
export const unreplaceSubject = (id: string) =>
  post<VerificationSubject>(proj(`/verification/subjects/${id}/unreplace`));
export const supplementRun = (runId: string, perStratum: number) =>
  post<{ added: number }>(proj(`/verification/runs/${runId}/supplement`), { perStratum });
export const refreshRun = (runId: string) =>
  post<{ marked: number; reopened: number; claims: number }>(
    proj(`/verification/runs/${runId}/refresh`),
  );
export const cancelRun = (runId: string, reason: string) =>
  post<VerificationRun>(proj(`/verification/runs/${runId}/cancel`), { reason });
export const subjectEvidencePath = (id: string, fileId: string) =>
  proj(`/verification/subjects/${id}/evidence/${fileId}`);
export const EVIDENCE_TYPES: Record<string, string> = {
  call_recording: "Call recording",
  field_visit: "Field visit",
  document: "Document",
  photo: "Photo",
  other: "Other",
};
export function addSubjectEvidence(id: string, evidenceType: string, files: File[]) {
  const f = new FormData();
  f.set("evidenceType", evidenceType);
  files.forEach((x) => f.append("files", x));
  return upload<{ items: { id: string; name: string }[] }>(
    proj(`/verification/subjects/${id}/evidence`),
    f,
  );
}
export const reviewSubject = (id: string, decision: "approve" | "reject", note?: string) =>
  post<VerificationSubject>(proj(`/verification/subjects/${id}/review`), { decision, note });
export const reviewQueue = () => get<VerificationSubject[]>(proj("/verification/review-queue"));
export const drawTier2 = (runId: string) =>
  post<{ runId: string }>(proj(`/verification/runs/${runId}/tier2`));
export const finalizeRun = (runId: string) =>
  post<VerificationRun>(proj(`/verification/runs/${runId}/finalize`));
export const koboExportUrl = (runId: string, format: "csv" | "xlsx" = "xlsx") =>
  `${proj(`/verification/runs/${runId}/kobo-export`)}?format=${format}`;
export function koboImport(runId: string, file: File) {
  const f = new FormData();
  f.set("file", file);
  return upload<{ matched: number; unmatched: number; updated: number }>(
    proj(`/verification/runs/${runId}/kobo-import`),
    f,
  );
}
export const listResults = () =>
  get<(VerificationRun & { finalisedAt: string })[]>(proj("/verification/results"));

/**
 * Derives the protocol status code from questionnaire answers (Q1 consent, Q10 completion, consistency).
 * Mirrors the server rule `verification/questionnaire.rules.ts`; shown to the enumerator before submit.
 */
export function deriveStatus(answers: Record<string, string>): StatusCode | undefined {
  const a = (k: string) => answers[k];
  if (a("q1") === "no") return "V-REF";
  if (a("q1") !== "yes") return undefined;
  if (a("q2") === "not_correct" && a("q3") === "not_correct") return "V-INC";
  if (a("q10") === "no") return "V-NCOMP";
  if (a("q10") === "not_sure") return "V-INC";
  if (a("q10") === "yes") return "V-COMP";
  return undefined;
}
