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 { readTable, toXlsx } from "../../core/files/table.js";
import { DomainError, type FieldError } from "../../core/http/errors.js";
import { can, classInScope, conflict, invalid, like, notFound, paging, scope, type Ctx } from "../../core/http/route.js";
import { cached } from "../../core/cache.js";
import { addDays, dmy, isDate, parseFormDate, today } from "../../shared/dates.js";
import { allClasses, getClassView } from "../delivery/index.js";
import { queueKpis } from "../projects/index.js";
import { buildOutcomeTemplateCsvBody, OUTCOME_TEMPLATE_DEFS } from "./template-catalogue.js";
import { syncOpenRuns } from "../verification/index.js";
import { checkPlacement, COLUMNS, JOB, PLACEMENT, SUPPORT, yesNo } from "./placement.rules.js";
import { refreshClassOutcomes } from "./status.service.js";

/** Order, due day after class end, what must be accepted first, and who is listed. */
export const REPORTS = [
  { type: "dropout", stage: "", label: "Dropout", after: 7, needs: null, listed: "1=1" },
  { type: "completion", stage: "", label: "Completion", after: 21, needs: "dropout", listed: "s.dropout_status<>'yes'" },
  { type: "certification", stage: "", label: "Certification", after: 45, needs: "completion", listed: "s.completion_status='yes'" },
  { type: "employment_placement", stage: "", label: "Employment placement", after: 60, needs: "certification", listed: "s.certification_status='yes'" },
  { type: "locality_compliant", stage: "", label: "Locality", after: 70, needs: "employment_placement", listed: "s.placement_status='yes'" },
  { type: "job_retention_3m", stage: "", label: "Retention 3 m", after: 150, needs: "employment_placement", listed: "s.placement_status='yes'" },
] as const;
export type Report = (typeof REPORTS)[number];
const key = (type: string, stage: string) => (stage ? `${type}:${stage}` : type);
export const def = (type: string, stage = ""): Report => REPORTS.find((r) => r.type === type && r.stage === stage) ?? notFound("Report type");
const DROPOUT_REASONS = ["voluntary_withdrawal", "dismissal", "health", "economic", "migration", "found_job", "low_attendance_auto", "other"];
const NONCOMPLETION = ["failed_assessment", "incomplete_assignments", "insufficient_attendance", "other"];
const STATUS: Record<string, string> = { dropout: "dropout_status", completion: "completion_status", certification: "certification_status", employment_placement: "placement_status", locality_compliant: "locality_status", job_retention_3m: "retention_3m_status" };
/** Lines the system adds for people the report does not ask about, so every report holds the whole class. */
const AUTO = ["dropout", "earlier_step_no"];
const latest = (db: Db, classId: string) => query(db, "SELECT * FROM outcome_reports r WHERE class_id=? AND status IN ('accepted','returned','ready') AND id=(SELECT MAX(x.id) FROM outcome_reports x WHERE x.class_id=r.class_id AND x.report_type=r.report_type AND x.stage_key=r.stage_key AND x.status IN ('accepted','returned'))", [classId]);
const accepted = async (db: Db, classId: string, need: string) => { const [t, st] = need.split(":"); return Boolean(await one(db, "SELECT 1 AS x FROM outcome_reports WHERE class_id=? AND report_type=? AND stage_key=? AND status='accepted'", [classId, t!, st ?? ""])); };

function cells(reports: Row[], end: string, now = today()) {
  const by = new Map(reports.map((r) => [key(r["report_type"], r["stage_key"]), r]));
  return REPORTS.map((d) => {
    const r = by.get(key(d.type, d.stage)), due = addDays(end, d.after), blocked = d.needs && by.get(d.needs)?.["status"] !== "accepted";
    const state = r?.["status"] === "accepted" ? "accepted" : r?.["status"] === "returned" ? "returned" : now <= end ? "not_due" : blocked ? "blocked" : now > due ? "overdue" : "due";
    return { type: d.type, ...(d.stage ? { stageKey: d.stage } : {}), ...(r ? { reportId: r["id"], yes: r["yes_count"], no: r["no_count"] } : {}), state, dueDate: due, ...(blocked && !r ? { reason: `Waiting for ${REPORTS.find((x) => key(x.type, x.stage) === d.needs)!.label}` } : {}) };
  });
}
export async function classOutcomes(classId: string) { const k = (await one(pool, "SELECT effective_end AS e FROM training_classes WHERE id=?", [classId]))!; return cells(await latest(pool, classId), k["e"]); }
export async function board(c: Ctx) {
  const classes = (await allClasses(c)).filter((k) => k.status !== "cancelled"), all = classes.length ? await query(pool, "SELECT r.* FROM outcome_reports r WHERE r.class_id IN (?) AND r.status IN ('accepted','returned') ORDER BY r.id", [classes.map((k) => k.id as string)]) : [];
  const byClass = new Map<string, Row[]>();
  for (const r of all) byClass.set(r["class_id"], [...(byClass.get(r["class_id"]) ?? []), r]);
  const rows = classes.map((cls) => ({ cls, cells: cells(byClass.get(cls.id) ?? [], cls.effectiveEnd) })), n = (s: string) => rows.reduce((a, r) => a + r.cells.filter((x) => x.state === s).length, 0);
  return { rows, summary: { due: n("due"), overdue: n("overdue"), returned: n("returned"), accepted: n("accepted") } };
}
const listed = (db: Db, classId: string, d: Report, extra: string[] = []) => query(db, `SELECT t.id, t.trainee_code, t.external_beneficiary_id AS ext, CONCAT_WS(' ',t.first_name,t.father_name,t.grandfather_name) AS name, s.* FROM trainees t JOIN trainee_status s ON s.trainee_id=t.id WHERE t.class_id=? AND t.roster_status IN ('active','reserve') AND (${d.listed} ${extra.length ? "OR t.id IN (?)" : ""}) ORDER BY t.trainee_code`, extra.length ? [classId, extra] : [classId]);
async function gates(db: Db, cls: Row, d: Report) {
  const out: { label: string; ok: boolean; detail?: string }[] = [], now = today();
  out.push({ label: "Class has ended", ok: now > cls["effective_end"], ...(now <= cls["effective_end"] ? { detail: `Ends on ${dmy(cls["effective_end"])}` } : {}) });
  { const m = Number((await one(db, "SELECT COALESCE(SUM(att_missing_marks),0) AS n FROM trainee_status WHERE class_id=? AND roster_status IN ('active','reserve')", [cls["id"]]))!["n"]); out.push({ label: "Attendance is complete", ok: m === 0, ...(m ? { detail: `${m} marks are missing. Record every session day first.` } : {}) }); }
  if (d.needs) out.push({ label: `${REPORTS.find((r) => key(r.type, r.stage) === d.needs)!.label} report accepted`, ok: await accepted(db, cls["id"], d.needs) });
  // Attendance can be corrected after the dropout report, so every later report checks again that both agree.
  if (d.type !== "dropout") { const x = await query(db, "SELECT t.trainee_code AS code FROM trainee_status s JOIN trainees t ON t.id=s.trainee_id WHERE s.class_id=? AND s.roster_status IN ('active','reserve') AND s.system_dropout_final=1 AND s.dropout_status='no' ORDER BY 1", [cls["id"]]); out.push({ label: "Everyone below 80 % attendance is reported as a dropout", ok: !x.length, ...(x.length ? { detail: `Correct the dropout report for ${x.slice(0, 10).map((r) => r["code"]).join(", ")}${x.length > 10 ? ` and ${x.length - 10} more` : ""}` } : {}) }); }
  return out;
}
interface LineOut { traineeId: string; code: string; name: string; value?: "yes" | "no"; locked?: boolean; lockReason?: string; eventDate?: string; reason?: string; details?: Record<string, string> }
export async function context(c: Ctx, classId: string, type: string, stage?: string) {
  const cls = await classInScope(c, classId), v = await getClassView(c, classId), d = def(type, stage);
  const prev = await one(pool, "SELECT * FROM outcome_reports WHERE class_id=? AND report_type=? AND stage_key=? AND status IN ('accepted','returned') ORDER BY id DESC LIMIT 1", [classId, d.type, d.stage]);
  const old = new Map((prev ? await query(pool, "SELECT * FROM outcome_report_lines WHERE report_id=? AND COALESCE(reason_code,'') NOT IN (?)", [prev["id"], AUTO]) : []).map((l) => [String(l["trainee_id"]), l]));
  const people = await listed(pool, classId, d, prev ? [...old.keys()] : []);
  const lines = people.map((p): LineOut => { const o = old.get(String(p["id"])), sys = d.type === "dropout" && p["system_dropout_final"];
    return { traineeId: p["id"], code: p["trainee_code"], name: p["name"], ...(sys ? { value: "yes", locked: true, lockReason: `Attendance ${p["att_rate_final"]} % is below 80 %`, reason: o?.["reason_code"] ?? "low_attendance_auto", ...(o?.["event_date"] ? { eventDate: o["event_date"] } : {}) } : o ? { value: o["value"], ...(o["event_date"] ? { eventDate: o["event_date"] } : {}), ...(o["reason_code"] ? { reason: o["reason_code"] } : {}), details: Object.fromEntries(Object.entries(json<Row>(o["details_json"], {})).filter(([, x]) => typeof x === "string")) } : d.type === "dropout" ? { value: "no" } : {}) }; });
  const used = await one(pool, "SELECT 1 AS x FROM verification_runs r JOIN verification_subjects s ON s.run_id=r.id JOIN trainees t ON t.id=s.trainee_id WHERE t.class_id=? AND (r.report_type=? OR r.report_type IS NULL) LIMIT 1", [classId, d.type]);
  return { cls: { id: classId, code: v.code, trainingTitle: v.trainingTitle, locationName: v.locationName, effectiveEnd: v.effectiveEnd, providerCode: v.providerCode }, reportType: d.type, ...(d.stage ? { stageKey: d.stage } : {}), gates: await gates(pool, cls, d), lines, resubmission: prev?.["status"] === "accepted", verificationUsed: Boolean(used) };
}
export interface LineIn { traineeId: string; value?: "yes" | "no" | undefined; eventDate?: string | undefined; reason?: string | undefined; details?: Record<string, string> | undefined }
const MUST_DATE = new Set(["dropout", "completion", "certification"]);
/** All of V1's rules, plus strict dates: every reported Yes has a real date that is not in the future. */
async function check(db: Db, cls: Row, d: Report, lines: LineIn[], prevIds: string[]): Promise<void> {
  for (const g of await gates(db, cls, d)) if (!g.ok) throw new DomainError(422, "BLOCKED", `${d.label} report is blocked: ${g.label.toLowerCase()} is required first.${g.detail ? ` ${g.detail}.` : ""}`);
  const people = await listed(db, cls["id"], d, prevIds), by = new Map(people.map((p) => [String(p["id"]), p])), given = new Map(lines.map((l) => [l.traineeId, l])), errors: FieldError[] = [], start = cls["actual_start"] ?? cls["planned_start"];
  const bad = (t: string, code: string, message: string) => { const old = errors.find((e) => e.path === `lines.${t}`); if (old) old.message += ` ${message}`; else errors.push({ path: `lines.${t}`, code, message }); };
  if (given.size !== lines.length) throw new DomainError(422, "DUPLICATE_LINE", "A trainee appears twice.");
  for (const [t, p] of by) {
    const l = given.get(t);
    if (!l?.value) { bad(t, "REQUIRED", `${p["name"]}: choose Yes or No.`); continue; }
    if (l.eventDate && !isDate(l.eventDate)) bad(t, "DATE_INVALID", `${p["name"]}: the date is not real.`);
    else if (l.eventDate && l.eventDate > today()) bad(t, "DATE_FUTURE", `${p["name"]}: the date is in the future.`);
    else if (l.eventDate && l.eventDate < start) bad(t, "DATE_TOO_EARLY", `${p["name"]}: the date is before the class started (${start}).`);
    else if (l.value === "yes" && !l.eventDate && MUST_DATE.has(d.type)) bad(t, "DATE_REQUIRED", `${p["name"]}: enter the date.`);
    if (d.type === "dropout") {
      if (p["system_dropout_final"] && l.value !== "yes") bad(t, "SYSTEM_DROPOUT", `${p["name"]}: attendance ${p["att_rate_final"]} % is below 80 %, so this must be Yes. Correct the attendance first if it is wrong.`);
      if (l.value === "yes" && !DROPOUT_REASONS.includes(l.reason ?? "")) bad(t, "REASON_REQUIRED", `${p["name"]}: choose the dropout reason.`);
      if (l.value === "yes") for (const [k, col] of Object.entries(STATUS)) if (k !== "dropout" && p[col] === "yes") { bad(t, "CONTRADICTION", `${p["name"]}: dropout cannot be reported because ${k.replace(/_/g, " ")} is already Yes.`); break; }
    } else {
      if (l.value === "yes" && p["dropout_status"] === "yes") bad(t, "CONTRADICTION", `${p["name"]}: dropout is already reported.`);
      if (l.value === "yes" && d.type !== "completion" && d.needs && p[STATUS[d.needs]!] !== "yes") bad(t, "CONTRADICTION", `${p["name"]}: ${d.needs.replace(/_/g, " ")} must be Yes first.`);
      if (d.type === PLACEMENT) for (const x of checkPlacement(l.value, l.details ?? {}).problems) bad(t, "PLACEMENT", x.message);
      if (l.value === "no") for (const later of REPORTS) if (later.needs === key(d.type, d.stage) && p[STATUS[key(later.type, later.stage)]!] === "yes") bad(t, "CONTRADICTION", `${p["name"]}: ${later.label} is already Yes, so this cannot be No.`);
    }
  }
  for (const t of given.keys()) if (!by.has(t)) bad(t, "NOT_LISTED", "This trainee does not belong in this report.");
  if (!by.size) throw new DomainError(422, "EMPTY", "No trainee qualifies for this report.");
  if (errors.length) throw new DomainError(422, "VALIDATION", `${errors.length} rows need attention.`, errors.slice(0, 100));
}
interface Submission { stageKey?: string | undefined; lines: LineIn[]; reasonForChange?: string | undefined; filename?: string | undefined }
export async function submit(c: Ctx, classId: string, type: string, b: Submission) {
  return getReport(c, await transaction((tx) => submitIn(tx, c, classId, type, b)));
}
async function submitIn(tx: Db, c: Ctx, classId: string, type: string, b: Submission): Promise<string> {
  const cls = await classInScope(c, classId), d = def(type, b.stageKey);
    await one(tx, "SELECT id FROM training_classes WHERE id=? FOR UPDATE", [classId]);
    const versions = await query(tx, "SELECT * FROM outcome_reports WHERE class_id=? AND report_type=? AND stage_key=? ORDER BY id", [classId, d.type, d.stage]), old = versions.filter((v) => v["status"] === "accepted").at(-1);
    if (versions.some((v) => v["status"] === "ready")) conflict("WAITING_APPROVAL", "A corrected version is already waiting for M&E approval.");
    if (old && !b.reasonForChange?.trim()) invalid("reasonForChange", "Explain what changed.");
    const prevIds = old ? (await query(tx, "SELECT CAST(trainee_id AS CHAR) AS t FROM outcome_report_lines WHERE report_id=? AND COALESCE(reason_code,'') NOT IN (?)", [old["id"], AUTO])).map((x) => x["t"] as string) : [];
    await check(tx, cls, d, b.lines, prevIds);
    const yes = b.lines.filter((l) => l.value === "yes").length;
    const id = await insert(tx, "outcome_reports", { project_id: c.pid, provider_id: cls["provider_id"], training_id: cls["training_id"], site_id: cls["site_id"], class_id: classId, report_type: d.type, stage_key: d.stage, version_no: Math.max(0, ...versions.map((v) => v["version_no"] as number)) + 1, status: old ? "ready" : "accepted", source_filename: b.filename, rows_total: b.lines.length, yes_count: yes, no_count: b.lines.length - yes, reason_for_change: b.reasonForChange, supersedes_report_id: old?.["id"], submitted_by: c.user.id, submitted_at: new Date().toISOString().slice(0, 23).replace("T", " ") });
    await insertMany(tx, "outcome_report_lines", ["report_id", "trainee_id", "value", "event_date", "reason_code", "details_json"], b.lines.map((l) => [id, l.traineeId, l.value!, l.eventDate ?? null, l.reason ?? null, JSON.stringify(l.details ?? {})]));
    if (d.type === PLACEMENT) await savePlacement(tx, id, b.lines);
    const auto = d.type === "dropout" ? [] : await query(tx, "SELECT t.id, s.dropout_status='yes' AS dropout FROM trainees t JOIN trainee_status s ON s.trainee_id=t.id WHERE t.class_id=? AND t.roster_status IN ('active','reserve') AND t.id NOT IN (?)", [classId, b.lines.map((l) => l.traineeId)]);
    await insertMany(tx, "outcome_report_lines", ["report_id", "trainee_id", "value", "reason_code", "details_json"], auto.map((t) => [id, t["id"], "no", t["dropout"] ? "dropout" : "earlier_step_no", '{"source_type":"system"}']));
    await execute(tx, "UPDATE outcome_reports SET rows_total=rows_total+?, na_count=? WHERE id=?", [auto.length, auto.length, id]);
    if (!old) { await refreshClassOutcomes(tx, classId); await syncOpenRuns(tx, { classId }); await queueKpis(tx, c.pid); }
    await audit(tx, c, { module: "outcomes", action: old ? "resubmission_requested" : "report_submitted", entityType: "outcome_report", entityId: id, providerId: cls["provider_id"], summary: `${d.label} report of ${cls["code"]}: ${yes} yes, ${b.lines.length - yes} no`, after: { lines: b.lines, reason: b.reasonForChange } });
    return id;
}
/** The employment answers, each in its own column (details_json keeps what was typed). */
async function savePlacement(tx: Db, reportId: string, lines: LineIn[]): Promise<void> {
  const ids = new Map((await query(tx, "SELECT id, CAST(trainee_id AS CHAR) AS t FROM outcome_report_lines WHERE report_id=?", [reportId])).map((x) => [x["t"] as string, String(x["id"])])), cols = [...SUPPORT, ...JOB, "notes"];
  await insertMany(tx, "outcome_placement_details", ["line_id", ...cols.map((k) => k.replace(/^placement_/, ""))], lines.map((l) => { const v = checkPlacement(l.value!, l.details ?? {}).clean; return [ids.get(l.traineeId)!, ...cols.map((k) => (k.startsWith("placement_") || k === "has_business_license" ? (v[k] ? (v[k] === "yes" ? 1 : 0) : null) : (v[k] ?? null)))]; }));
}
const REP = `SELECT r.*, k.code AS classCode, p.code AS providerCode, t.title AS trainingTitle, u.name AS byName FROM outcome_reports r JOIN training_classes k ON k.id=r.class_id JOIN providers p ON p.id=r.provider_id JOIN trainings t ON t.id=r.training_id LEFT JOIN users u ON u.id=r.submitted_by`;
const view = (r: Row) => ({ id: r["id"], classId: r["class_id"], classCode: r["classCode"], providerCode: r["providerCode"], trainingTitle: r["trainingTitle"], reportType: r["report_type"], ...(r["stage_key"] ? { stageKey: r["stage_key"] } : {}), version: r["version_no"], status: r["status"], rowsTotal: r["rows_total"], yesCount: r["yes_count"], noCount: r["no_count"], naCount: r["na_count"] ?? 0, submittedAt: r["submitted_at"] ?? undefined, submittedBy: r["byName"] ?? undefined, reviewNote: r["review_note"] ?? undefined, reasonForChange: r["reason_for_change"] ?? undefined, needsApproval: r["status"] === "ready", lines: [] as Row[], versions: [] as Row[] });
async function row(c: Ctx, rid: string): Promise<Row> { const s = scope(c, { provider: "r.provider_id", cls: "r.class_id", site: "r.site_id" }); return (await one(pool, `${REP} WHERE r.id=? AND r.project_id=? AND ${s.sql}`, [rid, c.pid, ...s.args] as never[])) ?? notFound("Report"); }
export async function getReport(c: Ctx, rid: string) {
  const r = await row(c, rid), lines = await query(pool, "SELECT l.*, t.trainee_code, CONCAT_WS(' ',t.first_name,t.father_name,t.grandfather_name) AS name FROM outcome_report_lines l JOIN trainees t ON t.id=l.trainee_id WHERE l.report_id=? ORDER BY t.trainee_code", [rid]);
  return { ...view(r), lines: lines.map((l) => ({ traineeId: l["trainee_id"], code: l["trainee_code"], name: l["name"], value: l["value"], ...(l["event_date"] ? { eventDate: l["event_date"] } : {}), ...(l["reason_code"] ? { reason: l["reason_code"] } : {}), details: Object.fromEntries(Object.entries(json<Row>(l["details_json"], {})).filter(([k, x]) => typeof x === "string" && (can(c, "trainee.view_pii") || !/^employer_(contact|email|phone)/.test(k)))) })),
    versions: await query(pool, "SELECT id, version_no AS version, status, submitted_at AS submittedAt FROM outcome_reports WHERE class_id=? AND report_type=? AND stage_key=? ORDER BY id DESC", [r["class_id"], r["report_type"], r["stage_key"]]) };
}
export async function listReports(c: Ctx) {
  const q = c.query, s = scope(c, { provider: "r.provider_id", cls: "r.class_id", site: "r.site_id" }), pg = paging(q), where = ["r.project_id=?", s.sql], args: unknown[] = [c.pid, ...s.args];
  for (const [k, col] of [["status", "r.status"], ["type", "r.report_type"], ["classId", "r.class_id"], ["providerId", "r.provider_id"], ["trainingId", "r.training_id"]] as const) if (q[k]) { where.push(`${col}=?`); args.push(q[k]); }
  if (q["needsApproval"] === "true") where.push("r.status='ready'");
  const w = where.join(" AND ");
  return { items: (await query(pool, `${REP} WHERE ${w} ORDER BY r.id DESC LIMIT ? OFFSET ?`, [...args, pg.pageSize, pg.offset] as never[])).map(view), page: pg.page, pageSize: pg.pageSize, total: (await one(pool, `SELECT COUNT(*) AS n FROM outcome_reports r WHERE ${w}`, args as never[]))!["n"] };
}
/** A report that later reports depend on cannot be taken back before those (V1 rule). */
async function assertLast(db: Db, r: Row): Promise<void> {
  const k = key(r["report_type"], r["stage_key"]);
  for (const d of REPORTS) if (d.needs === k && (await one(db, "SELECT 1 AS x FROM outcome_reports WHERE class_id=? AND report_type=? AND stage_key=? AND status='accepted'", [r["class_id"], d.type, d.stage]))) conflict("LATER_REPORT_EXISTS", `The ${d.label} report depends on this one. Return that report first.`);
}
async function takeBack(c: Ctx, rid: string, status: "returned" | "discarded", note: string) {
  const r = await row(c, rid);
  await transaction(async (tx) => {
    await one(tx, "SELECT id FROM training_classes WHERE id=? FOR UPDATE", [r["class_id"]]);
    await assertLast(tx, r);
    if (!(await execute(tx, "UPDATE outcome_reports SET status=?, reviewed_by=?, reviewed_at=UTC_TIMESTAMP(3), review_note=? WHERE id=? AND status='accepted'", [status, c.user.id, note, rid])).affectedRows) conflict("NOT_ACCEPTED", "Only an accepted report can be taken back.");
    await execute(tx, "UPDATE outcome_reports SET status='discarded', review_note=? WHERE class_id=? AND report_type=? AND stage_key=? AND status='ready'", [`Replaced: ${note}`.slice(0, 480), r["class_id"], r["report_type"], r["stage_key"]]);
    await refreshClassOutcomes(tx, r["class_id"]);
    await syncOpenRuns(tx, { classId: r["class_id"] });
    await queueKpis(tx, c.pid);
    await audit(tx, c, { module: "outcomes", action: `report_${status}`, entityType: "outcome_report", entityId: rid, providerId: r["provider_id"], summary: `${r["report_type"]} report of ${r["classCode"]} ${status}`, after: { note } });
  });
  return getReport(c, rid);
}
export const returnReport = (c: Ctx, rid: string, reason: string) => takeBack(c, rid, "returned", reason);
export const discardReport = (c: Ctx, rid: string, reason: string) => takeBack(c, rid, "discarded", reason);
export async function decideResubmission(c: Ctx, rid: string, decision: "approve" | "reject", note: string) {
  const r = await row(c, rid);
  if (decision === "reject" && !note.trim()) invalid("note", "Write a note before you reject.");
  await transaction(async (tx) => {
    const cls = (await one(tx, "SELECT * FROM training_classes WHERE id=? FOR UPDATE", [r["class_id"]]))!;
    if (!(await execute(tx, "UPDATE outcome_reports SET status=?, reviewed_by=?, reviewed_at=UTC_TIMESTAMP(3), review_note=? WHERE id=? AND status='ready'", [decision === "approve" ? "accepted" : "discarded", c.user.id, note, rid])).affectedRows) conflict("ALREADY_DECIDED", "This version is already decided.");
    if (decision === "approve") {
      // The facts may have changed since it was sent, so it is checked again before it replaces the old version.
      const ids = (await query(tx, "SELECT CAST(trainee_id AS CHAR) AS t, value, event_date, reason_code, details_json FROM outcome_report_lines WHERE report_id=? AND COALESCE(reason_code,'') NOT IN (?)", [rid, AUTO]));
      await check(tx, cls, def(r["report_type"], r["stage_key"]), ids.map((l) => ({ traineeId: l["t"] as string, value: l["value"] as "yes" | "no", eventDate: l["event_date"] ?? undefined, reason: l["reason_code"] ?? undefined, details: json<Record<string, string>>(l["details_json"], {}) })), ids.map((l) => l["t"] as string));
      await execute(tx, "UPDATE outcome_reports SET status='superseded' WHERE class_id=? AND report_type=? AND stage_key=? AND status='accepted' AND id<>?", [r["class_id"], r["report_type"], r["stage_key"], rid]);
      await refreshClassOutcomes(tx, r["class_id"]);
      await syncOpenRuns(tx, { classId: r["class_id"] });
      await queueKpis(tx, c.pid);
    }
    await audit(tx, c, { module: "outcomes", action: `resubmission_${decision}`, entityType: "outcome_report", entityId: rid, providerId: r["provider_id"], summary: `Corrected ${r["report_type"]} report of ${r["classCode"]}: ${decision}`, after: { note } });
  });
  return getReport(c, rid);
}
/** V1's template columns, filled with the trainees who belong in the report. */
export async function template(c: Ctx, classId: string, type: string, stage: string | undefined, format: string) {
  const x = await context(c, classId, type, stage), d = def(type, stage);
  return writeTemplate(d, `${d.type}_${x.cls.code}`, await templateRows(classId, d, x.lines), format);
}
async function templateRows(classId: string, d: Report, lines: LineOut[]): Promise<Record<string, string>[]> {
  const ext = new Map((await query(pool, "SELECT id, external_beneficiary_id AS e FROM trainees WHERE class_id=?", [classId])).map((t) => [String(t["id"]), t["e"] as string | null]));
  return lines.map((l) => ({ ...(d.type === PLACEMENT ? l.details : {}), external_beneficiary_id: ext.get(String(l.traineeId)) ?? "", trainee_unique_id: l.code, trainee_name: l.name, outcome_type: d.type, reported_value: l.value ? (d.type === PLACEMENT ? (l.value === "yes" ? "Yes" : "No") : l.value === "yes" ? "Y" : "N") : "", status_date: l.eventDate ?? "", [`${d.type}_date`]: l.eventDate ?? "", dropout_reason: d.type === "dropout" && l.value === "yes" ? (l.reason ?? "") : "", dropout_notes: "" }) as Record<string, string>);
}
async function writeTemplate(d: Report, name: string, rows: Record<string, string>[], format: string) {
  if (d.type === "dropout") rows.sort((a, b) => (a["reported_value"] === b["reported_value"] ? a["trainee_unique_id"]!.localeCompare(b["trainee_unique_id"]!) : a["reported_value"] === "Y" ? -1 : 1));
  const file = name.replace(/[^\w.-]+/g, "_"), cols = OUTCOME_TEMPLATE_DEFS.find((t) => t.reportType === d.type)!.columns.map((k) => k.key);
  if (format === "csv") return { name: `${file}.csv`, body: rows.length || d.type !== PLACEMENT ? buildOutcomeTemplateCsvBody(d.type, rows)! : `${cols.join(",")}\n`, xlsx: false };
  return { name: `${file}.xlsx`, body: await toXlsx(d.label, cols, rows.map((r) => cols.map((k) => r[k] ?? "")), cols), xlsx: true };
}
export const templates = () => OUTCOME_TEMPLATE_DEFS;
const normReason = (raw: string) => { const v = raw.trim().toLowerCase(); if (!v) return undefined; if (DROPOUT_REASONS.includes(v) || NONCOMPLETION.includes(v)) return v; return v.includes("voluntary") || v.includes("withdraw") ? "voluntary_withdrawal" : v.includes("dismiss") ? "dismissal" : v.includes("health") ? "health" : v.includes("economic") || v.includes("financial") ? "economic" : v.includes("migration") || v.includes("relocat") ? "migration" : v.includes("found") ? "found_job" : v.includes("attendance") || v.includes("absen") ? "low_attendance_auto" : "other"; };
export async function parseFile(c: Ctx, classId: string, type: string, stage: string | undefined, name: string, data: Buffer) {
  return parseRows(c, classId, type, stage, await readRows(def(type, stage), name, data));
}
/** Reads the file and checks its columns. Every row keeps its number in the file. */
async function readRows(d: Report, name: string, data: Buffer): Promise<Row[]> {
  const { header, rows } = await readTable(name, data);
  if (!header.some((h) => ["trainee_unique_id", "trainee_id", "external_beneficiary_id"].includes(h)) || !header.includes("reported_value")) throw new DomainError(422, "HEADER", "The file needs trainee_unique_id (or external_beneficiary_id) and reported_value. Use the template.");
  const missing = d.type === PLACEMENT ? COLUMNS.filter((k) => !header.includes(k)) : [];
  if (missing.length) throw new DomainError(422, "HEADER", `The file is not the employment placement template. Missing columns: ${missing.join(", ")}.`);
  return rows.map((r, i) => ({ ...r, __row: String(i + 2) }));
}
async function parseRows(c: Ctx, classId: string, type: string, stage: string | undefined, rows: Row[], inFile: { byRow?: Set<Row> } = {}) {
  const x = await context(c, classId, type, stage), d = def(type, stage), issues: { traineeCode: string; message: string }[] = [];
  const people = await query(pool, "SELECT id, trainee_code, external_beneficiary_id AS e FROM trainees WHERE class_id=?", [classId]), byKey = new Map<string, string>();
  for (const p of people) { byKey.set(String(p["trainee_code"]).toUpperCase(), p["id"]); byKey.set(String(p["id"]), p["id"]); if (p["e"]) byKey.set(`E:${String(p["e"]).toUpperCase()}`, p["id"]); }
  const lines = new Map(x.lines.map((l) => [String(l.traineeId), { ...l }])), seen = new Set<string>();
  for (const r of rows) {
    const code = r["trainee_unique_id"] || r["trainee_id"] || "", ext = r["external_beneficiary_id"] ?? "", id = byKey.get(code.toUpperCase()) ?? byKey.get(`E:${ext.toUpperCase()}`), label = code || ext, line = id ? lines.get(id) : undefined;
    const bad = (message: string) => issues.push({ traineeCode: label, message: dmy(`Row ${r["__row"]}: ${message}`) });
    if (inFile.byRow) { if (!id) continue; inFile.byRow.add(r); }
    if (!id) { bad("This trainee is not in the class."); continue; }
    if (!line) { bad("This trainee does not belong in this report."); continue; }
    if (seen.has(id)) { bad("This trainee appears twice in the file."); continue; }
    seen.add(id);
    if (r["outcome_type"] && r["outcome_type"] !== d.type) bad(`outcome_type must be "${d.type}".`);
    const v = (r["reported_value"] ?? "").trim().toLowerCase();
    if (yesNo(v) === "yes") line.value = "yes"; else if (yesNo(v) === "no") { if (line.locked) bad(`${line.lockReason}. It must be Y.`); else line.value = "no"; } else bad("reported_value must be Y or N.");
    const raw = r[`${d.type}_date`] || r["status_date"] || "";
    delete line.eventDate;
    if (raw) { const dt = parseFormDate(raw); if (!dt) bad(`The date "${raw}" is not valid. Use DD/MM/YYYY (day first), for example 25/03/2026.`); else if (dt > today()) bad(`The date ${dt} is in the future.`); else line.eventDate = dt; }
    const reason = normReason(r["dropout_reason"] || r["noncompletion_reason"] || r["reason"] || "");
    if (reason) line.reason = reason;
    const extra = Object.fromEntries(Object.entries(r).filter(([k, val]) => val && !["trainee_unique_id", "trainee_id", "trainee_name", "external_beneficiary_id", "outcome_type", "reported_value", "status_date", `${d.type}_date`, "dropout_reason"].includes(k)));
    delete extra["__row"];
    if (d.type === PLACEMENT) { const p = checkPlacement(line.value ?? "no", r as Record<string, string>); line.details = Object.fromEntries(Object.entries(p.clean).map(([k, v2]) => [k, String(v2)])); if (line.value) for (const e of p.problems) bad(e.message); }
    else if (Object.keys(extra).length) line.details = extra as Record<string, string>;
  }
  for (const [id, l] of lines) if (!seen.has(id)) issues.push({ traineeCode: l.code as string, message: "Missing from the file." });
  return { lines: [...lines.values()], issues };
}
async function siteClasses(c: Ctx, siteId: string) {
  const list = (await allClasses(c)).filter((k) => String(k.siteId) === siteId && k.status !== "cancelled");
  return list.length ? list : notFound("Location");
}
/** V1 uploads per training and location. The file covers every class there that is ready; each class still gets its own report. */
export async function siteContext(c: Ctx, siteId: string, type: string) {
  const list = await siteClasses(c, siteId), d = def(type), classes = [];
  for (const k of list) {
    const x = await context(c, k.id, type), waiting = Boolean(await one(pool, "SELECT 1 AS x FROM outcome_reports WHERE class_id=? AND report_type=? AND status='ready'", [k.id, d.type])), gate = x.gates.find((g) => !g.ok);
    const state = x.resubmission ? "accepted" : waiting ? "waiting" : gate ? "blocked" : !x.lines.length ? "empty" : "ready";
    classes.push({ id: k.id, code: k.code, state, reason: state === "blocked" ? [gate!.label, gate!.detail].filter(Boolean).join(": ") : state === "empty" ? "No trainee qualifies" : undefined, lines: x.lines });
  }
  return { siteId, reportType: d.type, label: d.label, providerCode: list[0]!.providerCode, trainingTitle: list[0]!.trainingTitle, locationName: list[0]!.locationName, classes };
}
export async function siteTemplate(c: Ctx, siteId: string, type: string, format: string) {
  const s = await siteContext(c, siteId, type), d = def(type), ready = s.classes.filter((k) => k.state === "ready"), rows = [];
  for (const k of ready) rows.push(...(await templateRows(k.id, d, k.lines)));
  if (!rows.length) conflict("NOTHING_READY", "No class of this location is ready for this report.");
  return writeTemplate(d, `${d.type}_${s.providerCode}_${s.locationName}`, rows, format);
}
export async function siteParse(c: Ctx, siteId: string, type: string, name: string, data: Buffer) {
  const s = await siteContext(c, siteId, type), rows = await readRows(def(type), name, data), seen = new Set<Row>(), classes = [], issues: { traineeCode: string; message: string }[] = [];
  for (const k of s.classes.filter((y) => y.state === "ready")) { const p = await parseRows(c, k.id, type, undefined, rows, { byRow: seen }); issues.push(...p.issues); classes.push({ id: k.id, code: k.code, lines: p.lines }); }
  for (const r of rows) if (!seen.has(r)) issues.push({ traineeCode: String(r["trainee_unique_id"] || r["external_beneficiary_id"] || ""), message: `Row ${r["__row"]}: This trainee is not in a class of this location that is ready for this report.` });
  return { classes, issues };
}
/** All classes or none. */
export async function siteSubmit(c: Ctx, siteId: string, type: string, b: { classes: { id: string; lines: LineIn[] }[]; filename?: string | undefined }) {
  const s = await siteContext(c, siteId, type), ready = new Set(s.classes.filter((k) => k.state === "ready").map((k) => String(k.id)));
  if (b.classes.some((k) => !ready.has(k.id)) || new Set(b.classes.map((k) => k.id)).size !== b.classes.length) conflict("NOT_READY", "A class is not ready for this report. Download the template again.");
  const ids = await transaction(async (tx) => { const out: string[] = []; for (const k of [...b.classes].sort((x, y) => Number(x.id) - Number(y.id))) out.push(await submitIn(tx, c, k.id, type, { lines: k.lines, filename: b.filename })); return out; });
  return { accepted: ids.length, reportIds: ids };
}
const FIELD: Record<string, string> = { dropout: "dropout_status", completion: "completion_status", certification: "certification_status", placement: "placement_status", locality: "locality_status", retention3m: "retention_3m_status" };
export async function statusList(c: Ctx) {
  const q = c.query, s = scope(c, { provider: "t.provider_id", cls: "t.class_id", site: "t.site_id" }), pg = paging(q), where = ["t.project_id=?", "t.roster_status IN ('active','reserve')", s.sql], args: unknown[] = [c.pid, ...s.args];
  for (const [k, col] of [["providerId", "t.provider_id"], ["classId", "t.class_id"]] as const) if (q[k]) { where.push(`${col}=?`); args.push(q[k]); }
  if (q["field"] && FIELD[q["field"]] && q["value"]) { where.push(`s.${FIELD[q["field"]]}=?`); args.push(q["value"]); }
  if (q["q"]) { where.push("(t.trainee_code LIKE ? OR CONCAT_WS(' ',t.first_name,t.father_name) LIKE ?)"); args.push(like(q["q"]), like(q["q"])); }
  const w = where.join(" AND "), from = "FROM trainees t JOIN trainee_status s ON s.trainee_id=t.id JOIN providers p ON p.id=t.provider_id JOIN training_classes k ON k.id=t.class_id";
  const ids = (await query(pool, `SELECT t.id FROM trainees t JOIN trainee_status s ON s.trainee_id=t.id WHERE ${w} ORDER BY t.trainee_code LIMIT ? OFFSET ?`, [...args, pg.pageSize, pg.offset] as never[])).map((x) => x["id"] as string);
  const rows = ids.length ? await query(pool, `SELECT t.id, t.trainee_code, CONCAT_WS(' ',t.first_name,t.father_name,t.grandfather_name) AS name, p.code AS pc, k.code AS kc, s.* ${from} WHERE t.id IN (?) ORDER BY t.trainee_code`, [ids]) : [];
  return { items: rows.map((r) => ({ traineeId: r["id"], code: r["trainee_code"], name: r["name"], providerCode: r["pc"], classCode: r["kc"], ...Object.fromEntries(Object.entries(FIELD).map(([k, col]) => [k, r[col]])), sources: { completion: r["completion_source"], certification: r["certification_source"], placement: r["placement_source"], locality: r["locality_source"], retention3m: r["retention_3m_source"] } })), page: pg.page, pageSize: pg.pageSize, total: (await one(pool, `SELECT COUNT(*) AS n FROM trainees t JOIN trainee_status s ON s.trainee_id=t.id WHERE ${w}`, args as never[]))!["n"] };
}
export const dropoutMonitoring = (c: Ctx) => cached(c, "dropouts", () => buildDropouts(c), 15);
async function buildDropouts(c: Ctx) {
  const q = c.query, s = scope(c, { provider: "t.provider_id", cls: "t.class_id", site: "t.site_id" }), extra = q["providerId"] ? " AND t.provider_id=?" : "", args = [c.pid, ...s.args, ...(q["providerId"] ? [q["providerId"]] : [])] as never[];
  const rows = (await query(pool, `SELECT t.id, t.trainee_code, CONCAT_WS(' ',t.first_name,t.father_name,t.grandfather_name) AS name, p.code AS pc, t.class_id, k.code AS kc, s.* FROM trainees t JOIN trainee_status s ON s.trainee_id=t.id JOIN providers p ON p.id=t.provider_id JOIN training_classes k ON k.id=t.class_id WHERE t.project_id=? AND t.roster_status IN ('active','reserve') AND ${s.sql}${extra} AND (s.system_dropout_risk OR s.system_dropout_final OR s.dropout_status='yes') ORDER BY s.att_rate_to_date LIMIT 5000`, args))
    .map((r) => ({ traineeId: r["id"], code: r["trainee_code"], name: r["name"], providerCode: r["pc"], classId: r["class_id"], classCode: r["kc"], rateToDate: r["att_rate_to_date"] ?? undefined, maxReachable: r["att_max_reachable"] ?? undefined, rateFinal: r["att_rate_final"] ?? undefined, atRisk: Boolean(r["system_dropout_risk"]), systemFinal: Boolean(r["system_dropout_final"]), tpReported: r["dropout_status"] === "yes", disputed: Boolean(r["att_dispute"]), missingInReport: Boolean(r["system_dropout_final"]) && r["dropout_status"] === "pending", reason: r["dropout_status"] === "yes" ? (r["dropout_reason"] ?? "other") : r["system_dropout_final"] ? "low_attendance_auto" : undefined }));
  // Provider staff see how many are at risk but not who, while the class runs: knowing could tempt them to mark absent trainees present.
  const seen = c.access.providerId ? rows.map((r) => (r.atRisk && !r.systemFinal && !r.tpReported ? { ...r, hidden: true, traineeId: "", code: "", name: "", rateToDate: undefined, maxReachable: undefined } : r)) : rows;
  const shown = seen.filter((r) => !q["flag"] || (r as unknown as Row)[q["flag"]]), reasons = new Map<string, number>();
  for (const r of rows) if (r.reason) reasons.set(r.reason, (reasons.get(r.reason) ?? 0) + 1);
  const snap = await one(pool, "SELECT value, target_value FROM kpi_snapshots WHERE project_id=? AND indicator_code='trainee_dropout_rate' AND layer='monitoring' AND provider_key=? ORDER BY as_of_date DESC LIMIT 1", [c.pid, c.access.providerId ?? q["providerId"] ?? "0"]);
  const buffers = await query(pool, `SELECT p.code, GREATEST(0, (SELECT COUNT(*) FROM trainees x WHERE x.provider_id=p.id AND x.roster_status IN ('active','reserve')) - COALESCE((SELECT k.target_trainees FROM provider_contracts k WHERE k.provider_id=p.id AND k.status='active' LIMIT 1),0)) AS n FROM providers p WHERE p.project_id=? ${c.access.providerId ? "AND p.id=?" : ""}`, c.access.providerId ? [c.pid, c.access.providerId] : [c.pid]);
  return { summary: { atRisk: rows.filter((r) => r.atRisk).length, systemFinal: rows.filter((r) => r.systemFinal).length, tpReported: rows.filter((r) => r.tpReported).length, disputed: rows.filter((r) => r.disputed).length, missingInReport: rows.filter((r) => r.missingInReport).length, effectiveRate: snap?.["value"] ?? undefined, target: snap?.["target_value"] ?? undefined, buffers: buffers.map((b) => ({ providerCode: b["code"], absorbed: Math.min(b["n"], rows.filter((r) => r.providerCode === b["code"] && (r.tpReported || r.systemFinal)).length) })) }, rows: shown, reasons: [...reasons].map(([reason, count]) => ({ reason, count })).sort((a, b) => b.count - a.count) };
}
export const canReview = (c: Ctx) => can(c, "outcome.review");
