import { audit } from "../../core/audit/audit.js";
import { execute, insert, insertMany, json, one, pool, query, transaction, type Db, type Row } from "../../core/db/db.js";
import { storeFile } from "../../core/files/files.js";
import { readTable, toCsv, toXlsx } from "../../core/files/table.js";
import { DomainError } from "../../core/http/errors.js";
import { can, conflict, invalid, notFound, paging, sameProvider, type Ctx, type Upload } from "../../core/http/route.js";
import { defineJob, enqueue } from "../../core/jobs/jobs.js";
import { candidatesFor } from "../duplicates/index.js";
import { assertClassOpen } from "../delivery/index.js";
import { enumLookup, maxRegistration, providerRules } from "./lookup.js";
import { afterRosterChange, assertOpen, insertTrainee, nextCodes } from "./registration.service.js";
import { canonicalHeader, checkTrainee, COLUMNS, type EnumLookup, type Issue, type Parsed } from "./trainee.rules.js";

const EXAMPLE: Record<string, string> = { first_name: "Abebe", father_name: "Kebede", grandfather_name: "Alemu", sex: "Male", age: "24", date_of_birth: "25/03/2002", phone: "0911223344", region: "Addis Ababa", woreda: "05", education: "Diploma", employment: "Not currently working", class_code: "", roster_status: "Active", form_date: "15/11/2026", consent_accuracy: "Yes", consent_contact_verify: "Yes" };
export async function template(c: Ctx) {
  const header = COLUMNS.map((x) => x.key), cls = c.query["classId"] ? await one(pool, "SELECT code FROM training_classes WHERE id=? AND project_id=?", [c.query["classId"], c.pid]) : undefined;
  const row = header.map((h) => (h === "class_code" ? (cls?.["code"] ?? "") : EXAMPLE[h] ?? ""));
  const xlsx = c.query["format"] === "xlsx";
  return { name: `trainee_registration_template.${xlsx ? "xlsx" : "csv"}`, xlsx, body: xlsx ? await toXlsx("Trainees", header, [row], header) : `${toCsv(header, []).trim().replace(/^﻿/, "")}\r\n` };
}
interface Target { providerId: string; trainingId: string; siteId: string; classId?: string; label: string; mode: "import" | "check_only" }
export async function start(c: Ctx, u: Upload) {
  const f = u.files[0] ?? invalid("file", "Choose a file."), providerId = u.fields["providerId"] ?? c.access.providerId ?? invalid("providerId", "Choose the provider.");
  sameProvider(c, providerId);
  const site = (await one(pool, "SELECT s.*, t.title FROM training_sites s JOIN trainings t ON t.id=s.training_id WHERE s.id=? AND s.provider_id=? AND s.project_id=?", [u.fields["siteId"] ?? "0", providerId, c.pid])) ?? invalid("siteId", "Choose the site.");
  if ((c.access.siteIds.length || c.access.classIds.length) && !c.access.siteIds.includes(site["id"])) notFound("Site");
  const mode = u.fields["mode"] === "check_only" ? "check_only" : "import";
  if (mode === "import") assertOpen(await providerRules(pool, providerId), 0);
  const target: Target = { providerId, trainingId: site["training_id"], siteId: site["id"], label: site["display_name"], mode, ...(u.fields["classId"] ? { classId: u.fields["classId"] } : {}) };
  const { header, rows } = await readTable(f.name, f.data, 5000);
  const headers = header.map(canonicalHeader), missing = COLUMNS.filter((x) => x.required && !headers.includes(x.key) && !(x.key === "class_code" && target.classId)).map((x) => `Missing required column "${x.key}"`);
  return transaction(async (tx) => {
    const fileId = await storeFile(tx, { projectId: c.pid, purpose: "import_source", name: f.name, data: f.data, userId: c.user.id });
    const bid = await insert(tx, "import_batches", { project_id: c.pid, provider_id: providerId, kind: mode === "check_only" ? "roster_check" : "trainees", target_json: JSON.stringify({ ...target, headerIssues: missing }), file_id: fileId, status: "validating", rows_total: rows.length, created_by: c.user.id });
    await insertMany(tx, "import_rows", ["batch_id", "row_no", "raw_json", "decision", "status"], rows.map((r, i) => [bid, i + 2, JSON.stringify(Object.fromEntries(Object.entries(r).map(([k, v]) => [canonicalHeader(k), v]))), "import", "ok"]));
    const jobId = await enqueue(tx, "imports.validate", { batchId: bid }, { projectId: c.pid, userId: c.user.id });
    return { batchId: bid, jobId };
  });
}
interface World { lookup: EnumLookup; provider: Row; classes: Map<string, Row>; phones: Map<string, string>; ext: Map<string, string>; target: Target; closed: Map<string, string> }
async function world(db: Db, b: Row): Promise<World> {
  const target = json<Target>(b["target_json"], {} as Target), classes = await query(db, "SELECT * FROM training_classes WHERE site_id=?", [target.siteId]);
  const t = await query(db, "SELECT phone_e164 AS p, external_beneficiary_id AS e, provider_id, trainee_code AS code FROM trainees WHERE project_id=? AND roster_status IN ('active','reserve')", [b["project_id"]]);
  const closed = new Map<string, string>();
  for (const k of classes) await assertClassOpen(db, k["id"]).catch((e: Error) => { closed.set(k["id"], e.message); });
  return { closed, lookup: await enumLookup(db), provider: await providerRules(db, target.providerId), target, classes: new Map(classes.map((k) => [String(k["code"]).toLowerCase(), k])), phones: new Map(t.filter((x) => x["p"]).map((x) => [x["p"], x["code"]])), ext: new Map(t.filter((x) => x["e"] && x["provider_id"] === target.providerId).map((x) => [String(x["e"]).toLowerCase(), x["code"]])) };
}
const cell = (v: unknown) => (typeof v === "string" ? v.trim().toLowerCase() : "");
async function checkRow(db: Db, w: World, b: Row, values: Record<string, string>, counts: { phone: Map<string, number>; ext: Map<string, number> }) {
  const fixed = w.target.classId ? [...w.classes.values()].find((k) => k["id"] === w.target.classId) : undefined, v = { ...values, ...(fixed && !values["class_code"] ? { class_code: fixed["code"] as string } : {}) };
  const { row, issues } = checkTrainee(v, { lookup: w.lookup, requireExternalId: Boolean(w.provider["requires_external_id"]), externalIdLabel: w.provider["external_id_label"] });
  const add = (field: string, code: string, message: string) => issues.push({ field, code, message, severity: "error" });
  const cls = w.classes.get(cell(v["class_code"]));
  if (v["class_code"] && !cls) add("class_code", "CLASS_UNKNOWN", `Class "${v["class_code"]}" does not belong to the selected site.`);
  else if (cls && w.closed.has(cls["id"]) && w.target.mode === "import") add("class_code", "REGISTRATION_CLOSED", w.closed.get(cls["id"])!);
  const phone = row["phone_e164"] as string | undefined, ext = cell(row["external_beneficiary_id"]);
  if (phone && w.phones.has(phone)) add("phone", "PHONE_DUPLICATE", `This phone number is already registered (${w.phones.get(phone)}).`);
  if (phone && (counts.phone.get(phone) ?? 0) > 1) add("phone", "PHONE_REPEATED", "This phone number appears more than once in the file.");
  if (ext && w.ext.has(ext)) add("external_beneficiary_id", "EXTERNAL_ID_DUPLICATE", `This ID is already used (${w.ext.get(ext)}).`);
  if (ext && (counts.ext.get(ext) ?? 0) > 1) add("external_beneficiary_id", "EXTERNAL_ID_REPEATED", "This ID appears more than once in the file.");
  const dup = row["first_name"] ? await candidatesFor(db, String(b["project_id"]), row as Row, 5) : [];
  return { row, cls, issues, dup: dup.map((d) => ({ traineeId: d.id, code: d.code, name: d.name, provider: d.provider, score: d.score, reasons: d.reasons })) };
}
const status = (issues: Issue[], dup: unknown[], note: string | null) => (issues.some((i) => i.severity === "error") ? "error" : dup.length && !note ? "duplicate" : issues.length ? "warning" : "ok");
async function tally(db: Db, bid: string): Promise<{ counts: Map<string, number>; ext: Map<string, number> }> {
  const { parsePhone } = await import("../../shared/phone.js"), counts = new Map<string, number>(), ext = new Map<string, number>();
  for (const r of await query(db, "SELECT raw_json FROM import_rows WHERE batch_id=? AND decision='import'", [bid])) { const v = json<Row>(r["raw_json"], {}), p = parsePhone(v["phone"] ?? ""), e = cell(v["external_beneficiary_id"]); if (p.ok) counts.set(p.e164, (counts.get(p.e164) ?? 0) + 1); if (e) ext.set(e, (ext.get(e) ?? 0) + 1); }
  return { counts, ext };
}
async function validate(db: Db, bid: string, only?: number[], progress?: (p: number) => Promise<void>): Promise<void> {
  const b = (await one(db, "SELECT * FROM import_batches WHERE id=?", [bid]))!, w = await world(db, b), t = await tally(db, bid);
  const rows = await query(db, `SELECT * FROM import_rows WHERE batch_id=? ${only ? "AND row_no IN (?)" : ""} ORDER BY row_no`, only ? [bid, only] : [bid]);
  for (const [i, r] of rows.entries()) {
    const x = await checkRow(db, w, b, json(r["raw_json"], {}), { phone: t.counts, ext: t.ext });
    await execute(db, "UPDATE import_rows SET parsed_json=?, errors_json=?, duplicates_json=?, status=? WHERE batch_id=? AND row_no=?", [JSON.stringify({ ...x.row, class_id: x.cls?.["id"] }), JSON.stringify(x.issues), JSON.stringify(x.dup), status(x.issues, x.dup, r["decision_note"]), bid, r["row_no"]]);
    if (progress && i % 100 === 99) await progress(Math.round((i / rows.length) * 100));
  }
  await refresh(db, bid);
}
async function refresh(db: Db, bid: string): Promise<void> {
  const n = (await one(db, "SELECT SUM(decision='import' AND status='error') AS e, SUM(decision='import' AND status='warning') AS w, SUM(decision='import' AND status='duplicate') AS d, SUM(decision='import' AND status='ok') AS o FROM import_rows WHERE batch_id=?", [bid]))!;
  const b = (await one(db, "SELECT target_json FROM import_batches WHERE id=?", [bid]))!, header = json<Row>(b["target_json"], {})["headerIssues"] as string[];
  await execute(db, "UPDATE import_batches SET rows_error=?, rows_warning=?, rows_duplicate=?, rows_valid=?, status=? WHERE id=?", [n["e"] ?? 0, n["w"] ?? 0, n["d"] ?? 0, n["o"] ?? 0, n["e"] || n["d"] || header.length ? "has_errors" : "ready", bid]);
}
defineJob("imports.validate", async (job) => { await validate(pool, String(job.payload["batchId"]), undefined, (p) => job.progress(p, "Checking rows")); return { message: "The file is checked." }; });
const BATCH = "SELECT b.*, u.name AS createdName, f.original_name AS fileName, (SELECT COUNT(*) FROM import_rows r WHERE r.batch_id=b.id AND r.decision='skip') AS skipped, (SELECT COUNT(*) FROM import_rows r WHERE r.batch_id=b.id AND r.created_entity_id IS NOT NULL) AS created FROM import_batches b LEFT JOIN users u ON u.id=b.created_by LEFT JOIN files f ON f.id=b.file_id";
async function batchView(b: Row) {
  const t = json<Target & { headerIssues: string[] }>(b["target_json"], {} as never), p = await providerRules(pool, t.providerId);
  return { id: b["id"], kind: b["kind"], mode: t.mode, status: b["status"], fileName: b["fileName"] ?? "", createdAt: b["created_at"], createdBy: b["createdName"] ?? "", target: { providerId: t.providerId, trainingId: t.trainingId, siteId: t.siteId, classId: t.classId, label: t.label }, counts: { total: b["rows_total"], valid: b["rows_valid"], error: b["rows_error"], warning: b["rows_warning"], duplicate: b["rows_duplicate"], skipped: b["skipped"], created: b["created"] },
    capacity: { registered: p["registered"], adding: b["rows_total"] - b["skipped"], max: maxRegistration(p["target"], p["pct"]) }, headerIssues: t.headerIssues };
}
async function batch(c: Ctx, bid: string): Promise<Row> { const b = (await one(pool, `${BATCH} WHERE b.id=? AND b.project_id=?`, [bid, c.pid])) ?? notFound("Import"); sameProvider(c, b["provider_id"]); if ((c.access.siteIds.length || c.access.classIds.length) && b["created_by"] !== c.user.id) notFound("Import"); return b; }
export const get = async (c: Ctx, bid: string) => batchView(await batch(c, bid));
export const list = async (c: Ctx) => Promise.all((await query(pool, `${BATCH} WHERE b.project_id=? ${c.access.providerId ? "AND b.provider_id=?" : ""} ORDER BY b.id DESC LIMIT 50`, c.access.providerId ? [c.pid, c.access.providerId] : [c.pid])).map(batchView));
const rowView = (r: Row) => ({ rowNo: r["row_no"], status: r["status"], values: json(r["raw_json"], {}), issues: json(r["errors_json"], []), duplicates: json(r["duplicates_json"], []), decision: r["decision"], decisionNote: r["decision_note"] ?? undefined });
export async function rows(c: Ctx, bid: string) {
  await batch(c, bid);
  const pg = paging(c.query), k = c.query["issue"] ?? "", where = ["error", "warning", "duplicate", "ok"].includes(k) ? "AND status=?" : "", args = where ? [bid, k] : [bid];
  return { items: (await query(pool, `SELECT * FROM import_rows WHERE batch_id=? ${where} ORDER BY row_no LIMIT ? OFFSET ?`, [...args, pg.pageSize, pg.offset])).map(rowView), page: pg.page, pageSize: pg.pageSize, total: (await one(pool, `SELECT COUNT(*) AS n FROM import_rows WHERE batch_id=? ${where}`, args))!["n"] };
}
const editable = (b: Row) => { if (!["ready", "has_errors"].includes(b["status"])) conflict("IMPORT_LOCKED", "This import can no longer be changed."); };
export async function fixRow(c: Ctx, bid: string, rowNo: number, values: Record<string, string>) {
  const b = await batch(c, bid);
  editable(b);
  const r = (await one(pool, "SELECT * FROM import_rows WHERE batch_id=? AND row_no=?", [bid, rowNo])) ?? notFound("Row"), old = json<Record<string, string>>(r["raw_json"], {}), next = { ...old, ...Object.fromEntries(Object.entries(values).filter(([k]) => COLUMNS.some((x) => x.key === k))) };
  await transaction(async (tx) => {
    await execute(tx, "UPDATE import_rows SET raw_json=?, decision_note=NULL WHERE batch_id=? AND row_no=?", [JSON.stringify(next), bid, rowNo]);
    const same = (await query(tx, "SELECT row_no, raw_json FROM import_rows WHERE batch_id=?", [bid])).filter((x) => { const v = json<Row>(x["raw_json"], {}); return x["row_no"] === rowNo || (["phone", "external_beneficiary_id"] as const).some((k) => v[k] && (v[k] === old[k] || v[k] === next[k])); }).map((x) => x["row_no"] as number);
    await validate(tx, bid, same);
  });
  return rowView((await one(pool, "SELECT * FROM import_rows WHERE batch_id=? AND row_no=?", [bid, rowNo]))!);
}
export async function decide(c: Ctx, bid: string, rowNo: number, decision: "skip" | "not_duplicate", reason?: string) {
  editable(await batch(c, bid));
  if (decision === "not_duplicate" && !reason?.trim()) invalid("reason", "Explain why this is a different person.");
  await transaction(async (tx) => {
    if (!(await execute(tx, "UPDATE import_rows SET decision=?, decision_note=? WHERE batch_id=? AND row_no=?", [decision === "skip" ? "skip" : "import", reason ?? "Skipped", bid, rowNo])).affectedRows) notFound("Row");
    await validate(tx, bid);
  });
  return rowView((await one(pool, "SELECT * FROM import_rows WHERE batch_id=? AND row_no=?", [bid, rowNo]))!);
}
export async function commit(c: Ctx, bid: string) {
  const b = await batch(c, bid);
  if (json<Target>(b["target_json"], {} as Target).mode === "check_only") conflict("CHECK_ONLY", "This file was only checked. Upload it as an import to register the trainees.");
  if (!can(c, "trainee.import")) notFound("Import");
  return transaction(async (tx) => {
    if (!(await execute(tx, "UPDATE import_batches SET status='committing' WHERE id=? AND status='ready'", [bid])).affectedRows) conflict("IMPORT_NOT_READY", "Fix or skip every row with a problem first.");
    // Told at once, not by a failed task: the gate and the limit of the contract.
    const b = (await one(tx, "SELECT target_json AS t FROM import_batches WHERE id=?", [bid]))!, n = (await one(tx, "SELECT COUNT(*) AS n FROM import_rows WHERE batch_id=? AND decision='import'", [bid]))!["n"] as number;
    assertOpen(await providerRules(tx, json<Target>(b["t"], {} as Target).providerId), n);
    return { jobId: await enqueue(tx, "imports.commit", { batchId: bid, ip: c.ip, role: c.access.roleCode }, { projectId: c.pid, userId: c.user.id }) };
  });
}
/** All rows are registered in one transaction: either everyone is in, or nobody. Everything is checked again first. */
defineJob("imports.commit", async (job) => {
  const bid = String(job.payload["batchId"]), c = { pid: job.projectId!, user: { id: job.userId! }, access: { roleCode: job.payload["role"] }, ip: job.payload["ip"], req: { id: `job_${job.id}` } } as unknown as Ctx;
  try {
    const n = await transaction(async (tx) => {
      const b = (await one(tx, "SELECT * FROM import_batches WHERE id=? FOR UPDATE", [bid]))!, target = json<Target>(b["target_json"], {} as Target);
      if (b["status"] !== "committing") throw new DomainError(409, "IMPORT_LOCKED", "This import is not waiting to be saved.");
      await one(tx, "SELECT id FROM providers WHERE id=? FOR UPDATE", [target.providerId]);
      await validate(tx, bid);
      const bad = (await one(tx, "SELECT COUNT(*) AS n FROM import_rows WHERE batch_id=? AND decision='import' AND status IN ('error','duplicate')", [bid]))!["n"];
      if (bad) throw new DomainError(409, "IMPORT_CHANGED", `${bad} rows have new problems since the check. Review them again.`);
      const rs = await query(tx, "SELECT * FROM import_rows WHERE batch_id=? AND decision='import' ORDER BY row_no", [bid]);
      assertOpen(await providerRules(tx, target.providerId), rs.length);
      const codes = await nextCodes(tx, target.providerId, rs.length), classes = new Map((await query(tx, "SELECT * FROM training_classes WHERE site_id=?", [target.siteId])).map((k) => [String(k["id"]), k]));
      for (const [i, r] of rs.entries()) {
        const { class_id: cid, ...row } = json<Parsed>(r["parsed_json"], {}), tid = await insertTrainee(tx, c, classes.get(String(cid))!, codes[i]!, row, { batchId: bid, raw: json(r["raw_json"], {}) });
        await execute(tx, "UPDATE import_rows SET created_entity_id=? WHERE batch_id=? AND row_no=?", [tid, bid, r["row_no"]]);
      }
      for (const cid of new Set(rs.map((r) => String(json<Row>(r["parsed_json"], {})["class_id"])))) await afterRosterChange(tx, c, cid);
      await execute(tx, "UPDATE import_batches SET status='committed', committed_at=UTC_TIMESTAMP(3) WHERE id=?", [bid]);
      await audit(tx, c, { module: "registration", action: "import_committed", entityType: "import", entityId: bid, providerId: target.providerId, summary: `Registered ${rs.length} trainees from a file`, after: { rows: rs.length } });
      return rs.length;
    });
    return { message: `${n} trainees registered.` };
  } catch (error) {
    await execute(pool, "UPDATE import_batches SET status='has_errors' WHERE id=? AND status='committing'", [bid]);
    throw error instanceof DomainError ? error : new DomainError(500, "IMPORT_FAILED", "The import failed and nothing was registered.");
  }
});
export async function discard(c: Ctx, bid: string) { editable(await batch(c, bid)); await execute(pool, "UPDATE import_batches SET status='discarded' WHERE id=?", [bid]); }
