import { audit } from "../../core/audit/audit.js";
import { execute, one, pool, query, transaction, type Db, type Row } from "../../core/db/db.js";
import { invalid, type Ctx } from "../../core/http/route.js";
import { afterRosterChange, rawTrainee } from "./registration.service.js";

/** Lines the system added by itself; they count as "not applicable" in a report. */
const AUTO = ["dropout", "earlier_step_no"];
const TYPE: Record<string, string> = { dropout: "Dropout", completion: "Completion", certification: "Certification", employment_placement: "Employment placement", locality_compliant: "Locality", job_retention_3m: "Job retention (3 months)" };

/** Everything that holds this trainee, so the person deleting sees it first. */
async function gather(db: Db, tid: string) {
  const n = async (sql: string) => Number((await one(db, sql, [tid]))!["n"]);
  const lines = await query(db, "SELECT r.id, r.report_type, r.version_no, r.status, l.value, k.code AS cls FROM outcome_report_lines l JOIN outcome_reports r ON r.id=l.report_id JOIN training_classes k ON k.id=r.class_id WHERE l.trainee_id=? ORDER BY r.id", [tid]);
  const subjects = await query(db, `SELECT r.id, r.indicator_code, r.status AS run_status, s.role, s.status_code, s.verified_value, (SELECT COUNT(*) FROM verification_evidence e WHERE e.subject_id=s.id) AS files
    FROM verification_subjects s JOIN verification_runs r ON r.id=s.run_id WHERE s.trainee_id=? ORDER BY r.id`, [tid]);
  const frames = await query(db, "SELECT r.id, r.indicator_code, r.status FROM verification_frame_members f JOIN verification_runs r ON r.id=f.run_id WHERE f.trainee_id=?", [tid]);
  return {
    lines, subjects, frames,
    marks: await n("SELECT COUNT(*) AS n FROM attendance_marks WHERE trainee_id=?"),
    corrections: await n("SELECT COUNT(*) AS n FROM attendance_corrections WHERE trainee_id=?"),
    placement: await n("SELECT COUNT(*) AS n FROM outcome_placement_details d JOIN outcome_report_lines l ON l.id=d.line_id WHERE l.trainee_id=?"),
    dropoutLists: await n("SELECT COUNT(*) AS n FROM verification_run_dropouts WHERE trainee_id=?"),
    duplicates: Number((await one(db, "SELECT COUNT(*) AS n FROM duplicate_candidates WHERE trainee_a_id=? OR trainee_b_id=?", [tid, tid]))!["n"]),
    snapshots: await n("SELECT COUNT(*) AS n FROM roster_snapshot_members WHERE trainee_id=?"),
    requests: await n("SELECT COUNT(*) AS n FROM roster_change_requests WHERE trainee_id=?"),
    replacedBy: await n("SELECT COUNT(*) AS n FROM trainees WHERE replaces_trainee_id=?"),
  };
}

export async function deleteImpact(c: Ctx, tid: string) {
  const t = await rawTrainee(c, tid), g = await gather(pool, tid), warnings: string[] = [];
  const runLabel = (r: Row) => `sample ${r["id"]} (${String(r["indicator_code"]).replace(/_/g, " ")})`;
  for (const s of g.subjects) {
    if (s["run_status"] === "finalised") warnings.push(`Already verified in the finished ${runLabel(s)}${s["status_code"] ? ` with result ${s["status_code"]}` : ""}. The person is removed from it, but the sample's stored result is not calculated again.`);
    else if (s["run_status"] !== "cancelled") warnings.push(`In the open ${runLabel(s)} as ${s["role"]}${s["status_code"] ? `, already recorded as ${s["status_code"]}` : ", not called yet"}. The sample will have one person less: replace them with a reserve if needed.`);
  }
  const accepted = g.lines.filter((l) => l["status"] === "accepted");
  if (accepted.length) warnings.push(`Counted in ${accepted.length} accepted outcome report${accepted.length === 1 ? "" : "s"}. Their totals and the indicators go down by one.`);
  if (g.replacedBy) warnings.push("Another trainee is recorded as replacing this person. That link is removed.");
  const items = [
    { area: "Attendance", count: g.marks, detail: g.marks ? [`${g.marks} attendance marks`, ...(g.corrections ? [`${g.corrections} correction requests`] : [])] : [] },
    { area: "Outcome reports", count: g.lines.length, detail: g.lines.map((l) => `${TYPE[l["report_type"]] ?? l["report_type"]} report ${l["id"]} of ${l["cls"]} (version ${l["version_no"]}, ${l["status"]}): ${l["value"]}`).concat(g.placement ? [`${g.placement} employment placement answers`] : []) },
    { area: "Verification", count: g.subjects.length + g.frames.length + g.dropoutLists, detail: [...g.subjects.map((s) => `Sampled in ${runLabel(s)} (${s["run_status"]}) as ${s["role"]}${s["status_code"] ? `, result ${s["status_code"]}` : ""}${Number(s["files"]) ? `, ${s["files"]} evidence files` : ""}`), ...g.frames.filter((f) => !g.subjects.some((s) => s["id"] === f["id"])).map((f) => `In the list sampled from for ${runLabel(f)} (${f["status"]}), not drawn`), ...(g.dropoutLists ? [`On ${g.dropoutLists} sample dropout lists`] : [])] },
    { area: "Registration", count: 1 + g.snapshots + g.requests + g.duplicates, detail: [`The trainee record and all its results`, ...(g.snapshots ? [`${g.snapshots} saved class lists`] : []), ...(g.requests ? [`${g.requests} roster change requests`] : []), ...(g.duplicates ? [`${g.duplicates} possible-duplicate pairs`] : [])] },
  ].filter((x) => x.count > 0);
  return { trainee: { id: t["id"], code: t["trainee_code"], name: [t["first_name"], t["father_name"], t["grandfather_name"]].filter(Boolean).join(" "), rosterStatus: t["roster_status"] }, sampled: g.subjects.length > 0, items, warnings };
}

/** Removes the trainee everywhere. A full copy of every removed row goes into the audit log, so nothing is lost without trace. */
export async function deleteTrainee(c: Ctx, tid: string, b: { reason: string; confirmCode: string }) {
  const t = await rawTrainee(c, tid);
  if (b.confirmCode.trim().toUpperCase() !== String(t["trainee_code"]).toUpperCase()) invalid("confirmCode", `Type ${t["trainee_code"]} to confirm.`);
  const impact = await deleteImpact(c, tid);
  await transaction(async (tx) => {
    const all = async (sql: string) => query(tx, sql, [tid]);
    const copy = {
      trainee: t, status: await all("SELECT * FROM trainee_status WHERE trainee_id=?"), classHistory: await all("SELECT * FROM trainee_class_history WHERE trainee_id=?"),
      marks: await all("SELECT m.*, s.session_date, s.class_id FROM attendance_marks m JOIN attendance_sessions s ON s.id=m.session_id WHERE m.trainee_id=?"), corrections: await all("SELECT * FROM attendance_corrections WHERE trainee_id=?"),
      outcomeLines: await all("SELECT * FROM outcome_report_lines WHERE trainee_id=?"), placement: await all("SELECT d.* FROM outcome_placement_details d JOIN outcome_report_lines l ON l.id=d.line_id WHERE l.trainee_id=?"),
      subjects: await all("SELECT * FROM verification_subjects WHERE trainee_id=?"), responses: await all("SELECT x.* FROM verification_responses x JOIN verification_subjects s ON s.id=x.subject_id WHERE s.trainee_id=?"),
      attempts: await all("SELECT x.* FROM verification_call_attempts x JOIN verification_subjects s ON s.id=x.subject_id WHERE s.trainee_id=?"), evidence: await all("SELECT x.* FROM verification_evidence x JOIN verification_subjects s ON s.id=x.subject_id WHERE s.trainee_id=?"),
      frames: await all("SELECT * FROM verification_frame_members WHERE trainee_id=?"), runDropouts: await all("SELECT * FROM verification_run_dropouts WHERE trainee_id=?"),
      duplicates: await query(tx, "SELECT * FROM duplicate_candidates WHERE trainee_a_id=? OR trainee_b_id=?", [tid, tid]), snapshots: await all("SELECT * FROM roster_snapshot_members WHERE trainee_id=?"),
      requests: await all("SELECT * FROM roster_change_requests WHERE trainee_id=?"), replacedBy: await all("SELECT id, trainee_code FROM trainees WHERE replaces_trainee_id=?"),
    };
    const reports = [...new Set(copy.outcomeLines.map((l) => String(l["report_id"])))], sessions = [...new Set(copy.marks.map((m) => String(m["session_id"])))];
    const runs = [...new Set([...copy.subjects, ...copy.frames, ...copy.runDropouts].map((r) => String(r["run_id"])))], snaps = [...new Set(copy.snapshots.map((s) => String(s["snapshot_id"])))];
    // Evidence files are kept on disk (uploads are never destroyed) but no longer offered.
    if (copy.evidence.length) await execute(tx, "UPDATE files SET deleted_at=UTC_TIMESTAMP(3) WHERE id IN (?)", [copy.evidence.map((e) => String(e["file_id"]))]);
    await execute(tx, "DELETE FROM verification_subjects WHERE trainee_id=?", [tid]);
    await execute(tx, "DELETE FROM verification_frame_members WHERE trainee_id=?", [tid]);
    await execute(tx, "DELETE FROM verification_run_dropouts WHERE trainee_id=?", [tid]);
    await execute(tx, "DELETE FROM outcome_report_lines WHERE trainee_id=?", [tid]);
    await execute(tx, "DELETE FROM attendance_corrections WHERE trainee_id=?", [tid]);
    await execute(tx, "DELETE FROM attendance_marks WHERE trainee_id=?", [tid]);
    await execute(tx, "DELETE FROM duplicate_candidates WHERE trainee_a_id=? OR trainee_b_id=?", [tid, tid]);
    await execute(tx, "DELETE FROM roster_snapshot_members WHERE trainee_id=?", [tid]);
    await execute(tx, "DELETE FROM roster_change_requests WHERE trainee_id=?", [tid]);
    await execute(tx, "UPDATE trainees SET replaces_trainee_id=NULL WHERE replaces_trainee_id=?", [tid]);
    await execute(tx, "DELETE FROM trainees WHERE id=?", [tid]);
    // Totals that held the person are counted again.
    if (reports.length) await execute(tx, `UPDATE outcome_reports r SET rows_total=(SELECT COUNT(*) FROM outcome_report_lines l WHERE l.report_id=r.id), yes_count=(SELECT COUNT(*) FROM outcome_report_lines l WHERE l.report_id=r.id AND l.value='yes'),
      na_count=(SELECT COUNT(*) FROM outcome_report_lines l WHERE l.report_id=r.id AND COALESCE(l.reason_code,'') IN (?)), no_count=rows_total-yes_count-na_count WHERE r.id IN (?)`, [AUTO, reports]);
    if (sessions.length) await execute(tx, `UPDATE attendance_sessions s SET marks_count=(SELECT COUNT(*) FROM attendance_marks m WHERE m.session_id=s.id), present_count=(SELECT COUNT(*) FROM attendance_marks m WHERE m.session_id=s.id AND m.status=1),
      absent_count=(SELECT COUNT(*) FROM attendance_marks m WHERE m.session_id=s.id AND m.status=2), excused_count=(SELECT COUNT(*) FROM attendance_marks m WHERE m.session_id=s.id AND m.status=3) WHERE s.id IN (?)`, [sessions]);
    if (snaps.length) await execute(tx, "UPDATE roster_snapshots s SET members_count=(SELECT COUNT(*) FROM roster_snapshot_members m WHERE m.snapshot_id=s.id) WHERE s.id IN (?)", [snaps]);
    // Open samples count their people again; a finished sample keeps the result it was signed off with.
    for (const r of runs) await execute(tx, `UPDATE verification_runs r JOIN (SELECT ? AS run_id, COALESCE(SUM(role IN ('primary','replacement')),0) AS pr, COALESCE(SUM(role='reserve'),0) AS rs, COALESCE(SUM(status_code IS NOT NULL AND role<>'reserve'),0) AS done FROM verification_subjects WHERE run_id=?) k ON k.run_id=r.id
      SET r.cnt_primary=k.pr, r.cnt_reserve=k.rs, r.cnt_completed=k.done WHERE r.status NOT IN ('finalised','cancelled')`, [r, r]);
    await afterRosterChange(tx, c, String(t["class_id"]));
    await audit(tx, c, { module: "registration", action: "trainee_deleted", entityType: "trainee", entityId: tid, providerId: t["provider_id"], summary: `Deleted trainee ${t["trainee_code"]}: ${b.reason}`.slice(0, 480), before: copy, after: { reason: b.reason, removed: impact.items } });
  });
  return { deleted: t["trainee_code"], items: impact.items };
}
