import { execute, one, pool, query, type Row } from "../../core/db/db.js";
import { scope, type Ctx } from "../../core/http/route.js";
import { defineJob, enqueue } from "../../core/jobs/jobs.js";

interface Check { key: string; severity: "error" | "warning" | "info"; entity: string; message: string; href: string; sql: string }
/** Each query returns provider_id and entity_id of what needs attention. */
const CHECKS: Check[] = [
  { key: "Form date unclear", severity: "info", entity: "trainee", message: "The day and month of the form date cannot be told apart.", href: "trainees", sql: "SELECT provider_id, id AS entity_id FROM trainees WHERE project_id=? AND form_date_confidence='ambiguous' AND roster_status IN ('active','reserve')" },
  { key: "Phone missing or invalid", severity: "warning", entity: "trainee", message: "The phone number is missing or not valid.", href: "trainees", sql: "SELECT provider_id, id AS entity_id FROM trainees WHERE project_id=? AND phone_e164 IS NULL AND roster_status IN ('active','reserve')" },
  { key: "Region unknown", severity: "info", entity: "trainee", message: "The region could not be recognised.", href: "trainees", sql: "SELECT provider_id, id AS entity_id FROM trainees WHERE project_id=? AND region_code IS NULL AND roster_status IN ('active','reserve')" },
  { key: "Eligibility unknown", severity: "warning", entity: "trainee", message: "Age, education or employment is missing.", href: "trainees", sql: "SELECT provider_id, id AS entity_id FROM trainees WHERE project_id=? AND eligibility_status='unknown' AND roster_status IN ('active','reserve')" },
  { key: "Attendance on a non-session day", severity: "info", entity: "class", message: "Attendance is recorded on a holiday or a day without a session. It is kept but not counted.", href: "classes", sql: "SELECT s.provider_id, s.class_id AS entity_id FROM attendance_sessions s LEFT JOIN class_calendar_days d ON d.class_id=s.class_id AND d.cal_date=s.session_date WHERE s.project_id=? AND COALESCE(d.kind,'none') NOT IN ('session','exempt') GROUP BY s.provider_id, s.class_id" },
  { key: "Attendance missing", severity: "warning", entity: "class", message: "Some days have no attendance.", href: "classes", sql: "SELECT c.provider_id, c.id AS entity_id FROM training_classes c JOIN class_counters k ON k.class_id=c.id WHERE c.project_id=? AND k.sessions_missing>0 AND c.is_cancelled=0" },
  { key: "Outcome date missing", severity: "info", entity: "trainee", message: "A result is Yes but has no date.", href: "trainees", sql: "SELECT DISTINCT r.provider_id, l.trainee_id AS entity_id FROM outcome_report_lines l JOIN outcome_reports r ON r.id=l.report_id WHERE r.project_id=? AND r.status='accepted' AND l.value='yes' AND l.event_date IS NULL AND r.report_type IN ('dropout','completion','certification')" },
  { key: "Low attendance reported as No dropout", severity: "warning", entity: "trainee", message: "Attendance is below 80 % but the provider reported no dropout.", href: "trainees", sql: "SELECT provider_id, trainee_id AS entity_id FROM trainee_status WHERE project_id=? AND att_dispute=1" },
  { key: "Evidence file missing", severity: "error", entity: "file", message: "An uploaded file is not in storage.", href: "obligations", sql: "SELECT s.provider_id, f.id AS entity_id FROM files f JOIN activity_submission_files x ON x.file_id=f.id JOIN activity_submissions s ON s.id=x.submission_id WHERE f.project_id=? AND (f.sha256 IS NULL OR f.sha256='')" },
  { key: "Contract date missing", severity: "warning", entity: "provider", message: "The contract has no signing date, so its activity dates cannot be set.", href: "providers", sql: "SELECT provider_id, provider_id AS entity_id FROM provider_contracts WHERE project_id=? AND status='active' AND signed_date IS NULL" },
  { key: "Duplicate phone", severity: "error", entity: "trainee", message: "Two active trainees share a phone number.", href: "duplicates", sql: "SELECT provider_id, id AS entity_id FROM trainees WHERE project_id=? AND roster_status IN ('active','reserve') AND phone_e164 IN (SELECT p FROM (SELECT phone_e164 AS p FROM trainees WHERE roster_status IN ('active','reserve') AND phone_e164 IS NOT NULL GROUP BY project_id, phone_e164 HAVING COUNT(*)>1) z)" },
];
export async function run(pid: string): Promise<number> {
  let total = 0;
  for (const k of CHECKS) {
    const rows = await query(pool, k.sql, [pid]), seen = new Set(rows.map((r) => String(r["entity_id"])));
    const old = new Map((await query(pool, "SELECT id, entity_id, resolved_at FROM datahealth_findings WHERE project_id=? AND check_key=?", [pid, k.key])).map((o) => [String(o["entity_id"]), o]));
    for (const r of rows) { const o = old.get(String(r["entity_id"])); if (o) await execute(pool, "UPDATE datahealth_findings SET last_seen_at=UTC_TIMESTAMP(3), resolved_at=NULL WHERE id=?", [o["id"]]); else await execute(pool, "INSERT INTO datahealth_findings (project_id, check_key, severity, provider_id, entity_type, entity_id, message, first_seen_at, last_seen_at) VALUES (?,?,?,?,?,?,?,UTC_TIMESTAMP(3),UTC_TIMESTAMP(3))", [pid, k.key, k.severity, r["provider_id"], k.entity, r["entity_id"], k.message]); }
    for (const [e, o] of old) if (!seen.has(e) && !o["resolved_at"]) await execute(pool, "UPDATE datahealth_findings SET resolved_at=UTC_TIMESTAMP(3) WHERE id=?", [o["id"]]);
    total += rows.length;
  }
  return total;
}
defineJob("datahealth.run", async (job) => ({ message: `${await run(job.projectId!)} things need attention.` }));
const LEVEL: Record<string, string> = { error: "high", warning: "medium", info: "low" };
const LINK: Record<string, (p: string, e: string) => string> = { trainee: (_p, e) => `trainees/${e}`, class: (_p, e) => `classes/${e}`, provider: (_p, e) => `providers/${e}`, file: () => "obligations" };
export async function findings(c: Ctx) {
  const s = scope(c, { provider: "f.provider_id" });
  const rows = await query(pool, `SELECT f.*, p.code AS pcode, t.trainee_code AS tcode, k.code AS kcode FROM datahealth_findings f LEFT JOIN providers p ON p.id=f.provider_id LEFT JOIN trainees t ON f.entity_type='trainee' AND t.id=f.entity_id LEFT JOIN training_classes k ON f.entity_type='class' AND k.id=f.entity_id WHERE f.project_id=? AND f.resolved_at IS NULL AND ${s.sql} ORDER BY FIELD(f.severity,'error','warning','info'), f.check_key, f.id LIMIT 3000`, [c.pid, ...s.args] as never[]);
  return { findings: rows.map((f) => ({ id: f["id"], check: f["check_key"], severity: LEVEL[f["severity"]], providerCode: f["pcode"] ?? "", entity: f["tcode"] ?? f["kcode"] ?? `${f["entity_type"]} ${f["entity_id"]}`, message: f["message"], href: LINK[f["entity_type"]]?.(c.pid, String(f["entity_id"])) ?? "dashboard", firstSeen: String(f["first_seen_at"]).slice(0, 10) })), providers: (await query(pool, `SELECT p.id, p.code, p.name, (SELECT SUM(f.severity='error')*10+LEAST(40,SUM(f.severity='warning')*2) FROM datahealth_findings f WHERE f.provider_id=p.id AND f.resolved_at IS NULL) AS lost FROM providers p WHERE project_id=? ${c.access.providerId ? "AND id=?" : ""} ORDER BY code`, c.access.providerId ? [c.pid, c.access.providerId] : [c.pid])).map((p) => ({ id: p["id"], code: p["code"], name: p["name"], dataHealth: Math.max(0, 100 - Number(p["lost"] ?? 0)) })) };
}
export async function summary(c: Ctx): Promise<Row[]> { const s = scope(c, { provider: "f.provider_id" }); return query(pool, `SELECT f.check_key AS \`check\`, f.severity, COUNT(*) AS count FROM datahealth_findings f WHERE f.project_id=? AND f.resolved_at IS NULL AND ${s.sql} GROUP BY f.check_key, f.severity`, [c.pid, ...s.args] as never[]); }
export const start = async (c: Ctx) => ({ jobId: await enqueue(pool, "datahealth.run", {}, { projectId: c.pid, userId: c.user.id }) });
void one;
