import { audit } from "../../core/audit/audit.js";
import { execute, insert, json, one, pool, query, transaction, update, type Db, type Row, type SqlValue } from "../../core/db/db.js";
import { openFile, storeEvidence, type Incoming } from "../../core/files/files.js";
import { DomainError } from "../../core/http/errors.js";
import { can, conflict, deny, invalid, notFound, paging, scope, type Ctx } from "../../core/http/route.js";
import { today } from "../../shared/dates.js";
import { queueKpis } from "../projects/index.js";
import { materialize, plan } from "./materialize.service.js";

const SEL = `SELECT o.*, d.code AS dcode, d.name AS dname, d.scope AS dscope, p.code AS pcode, p.name AS pname, t.title AS ttitle, st.display_name AS sname, k.code AS kcode FROM activity_obligations o JOIN activity_definitions d ON d.id=o.definition_id JOIN providers p ON p.id=o.provider_id LEFT JOIN trainings t ON t.id=o.training_id LEFT JOIN training_sites st ON st.id=o.site_id LEFT JOIN training_classes k ON k.id=o.class_id`;
const label = (o: Row) => `${o["kcode"] ? `${o["kcode"]} · ${o["ttitle"]}` : o["sname"] ?? o["ttitle"] ?? o["pname"]}${o["sequence_no"] > 1 ? ` · ${o["sequence_no"]}` : ""}`;
const view = (o: Row) => ({ id: o["id"], providerId: o["provider_id"], providerCode: o["pcode"], activity: { code: o["dcode"], name: o["dname"], scope: o["dscope"] }, scopeLabel: label(o), openDate: o["open_date"], dueDate: o["due_date"], closeDate: o["close_date"], status: o["status"], latestSubmissionId: o["latest_submission_id"] ?? undefined });
const S = (c: Ctx) => scope(c, { provider: "o.provider_id", cls: "o.class_id", site: "o.site_id" });
export async function list(c: Ctx) {
  const q = c.query, s = S(c), pg = paging(q), where = ["o.project_id=?", s.sql], args: unknown[] = [c.pid, ...s.args];
  for (const [k, col] of [["status", "o.status"], ["providerId", "o.provider_id"], ["definition", "d.code"]] as const) if (q[k]) { where.push(`${col}=?`); args.push(q[k]); }
  if (q["dueFrom"]) { where.push("o.due_date>=?"); args.push(q["dueFrom"]); }
  if (q["dueTo"]) { where.push("o.due_date<=?"); args.push(q["dueTo"]); }
  const w = where.join(" AND ");
  return { items: (await query(pool, `${SEL} WHERE ${w} ORDER BY o.due_date, o.id 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 activity_obligations o JOIN activity_definitions d ON d.id=o.definition_id WHERE ${w}`, args as never[]))!["n"] };
}
export const obligationsOfClass = async (c: Ctx, classId: string) => (await query(pool, `${SEL} WHERE o.class_id=? AND o.project_id=? ORDER BY o.due_date`, [classId, c.pid])).map(view);
const row = async (c: Ctx, oid: string): Promise<Row> => { const s = S(c); return (await one(pool, `${SEL} WHERE o.id=? AND o.project_id=? AND ${s.sql}`, [oid, c.pid, ...s.args] as never[])) ?? notFound("Obligation"); };
/** No types listed means any type, as in V1. */
interface Rules { types: string[]; minFiles: number; checklist: { key: string; label: string }[] }
const rules = (v: unknown): Rules => { const r = json<Partial<Rules>>(v, {}); return { types: r.types ?? [], minFiles: r.minFiles ?? 1, checklist: r.checklist ?? [] }; };
export async function get(c: Ctx, oid: string) {
  const o = await row(c, oid), d = (await one(pool, "SELECT * FROM activity_definitions WHERE id=?", [o["definition_id"]]))!, subs = await query(pool, "SELECT s.*, u.name AS byName, r.name AS revName FROM activity_submissions s LEFT JOIN users u ON u.id=s.submitted_by LEFT JOIN users r ON r.id=s.reviewed_by WHERE s.obligation_id=? ORDER BY s.version_no DESC", [oid]);
  const files = subs.length ? await query(pool, "SELECT x.submission_id, f.id, f.original_name, f.size_bytes FROM activity_submission_files x JOIN files f ON f.id=x.file_id WHERE x.submission_id IN (?)", [subs.map((s) => s["id"] as string)]) : [];
  return { ...view(o), providerName: o["pname"], activity: { code: d["code"], name: d["name"], scope: d["scope"], description: d["description"] ?? "", linkedIndicator: d["linked_indicator_code"] ?? undefined, evidence: rules(d["evidence_rules_json"]) },
    submissions: subs.map((s) => ({ id: s["id"], version: s["version_no"], status: s["status"], submittedAt: s["submitted_at"], submittedBy: s["byName"] ?? "", isLate: Boolean(s["is_late"]), files: files.filter((f) => f["submission_id"] === s["id"]).map((f) => ({ id: f["id"], name: f["original_name"], sizeKb: Math.ceil((f["size_bytes"] ?? 0) / 1024) })), checklist: json(s["checklist_json"], {}), note: s["note"] ?? undefined, ...(s["reviewed_at"] ? { review: { decidedBy: s["revName"] ?? "", decidedAt: s["reviewed_at"], note: s["review_note"] ?? undefined, items: json(s["review_json"], {}) } } : {}) })) };
}
export async function submit(c: Ctx, oid: string, u: { fields: Record<string, string>; files: Incoming[] }) {
  const o = await row(c, oid), d = (await one(pool, "SELECT * FROM activity_definitions WHERE id=?", [o["definition_id"]]))!, r = rules(d["evidence_rules_json"]), now = today();
  if (o["status"] === "approved") conflict("CLOSED", "This obligation is already settled.");
  if (now < o["open_date"]) conflict("NOT_OPEN", `This opens on ${o["open_date"]}.`);
  if (now > o["close_date"] && !["returned", "waived"].includes(o["status"])) conflict("WINDOW_CLOSED", `Submissions closed on ${o["close_date"]}. Ask M&E for an extension.`);
  if (u.files.length < r.minFiles) invalid("files", `Attach at least ${r.minFiles} file${r.minFiles === 1 ? "" : "s"}.`);
  if (r.types.length) for (const f of u.files) if (!r.types.includes((/\.(\w+)$/.exec(f.name)?.[1] ?? "").toLowerCase().replace("jpeg", "jpg"))) invalid("files", `${f.name}: use ${r.types.join(", ")}.`);
  let checklist: Record<string, boolean> = {};
  try { checklist = JSON.parse(u.fields["checklist"] || "{}") as Record<string, boolean>; } catch { invalid("checklist", "The checklist could not be read."); }
  const miss = r.checklist.find((k) => checklist[k.key] !== true);
  if (miss) invalid(`checklist.${miss.key}`, `Confirm: ${miss.label}`);
  await transaction(async (tx) => {
    const lock = (await one(tx, "SELECT status FROM activity_obligations WHERE id=? FOR UPDATE", [oid]))!;
    if (lock["status"] === "approved") conflict("CLOSED", "This obligation is already settled.");
    await execute(tx, "UPDATE activity_submissions SET status='superseded' WHERE obligation_id=? AND status='submitted'", [oid]);
    const v = Number((await one(tx, "SELECT COALESCE(MAX(version_no),0)+1 AS v FROM activity_submissions WHERE obligation_id=?", [oid]))!["v"]);
    const sid = await insert(tx, "activity_submissions", { obligation_id: oid, project_id: c.pid, provider_id: o["provider_id"], definition_id: o["definition_id"], version_no: v, checklist_json: JSON.stringify(checklist), note: u.fields["note"]?.slice(0, 2000), status: "submitted", is_late: now > o["due_date"], submitted_by: c.user.id, submitted_at: new Date().toISOString().slice(0, 23).replace("T", " ") });
    for (const f of u.files) await execute(tx, "INSERT INTO activity_submission_files (submission_id, file_id) VALUES (?,?)", [sid, await storeEvidence(tx, { projectId: c.pid, purpose: "activity_evidence", file: f, userId: c.user.id })]);
    await execute(tx, "UPDATE activity_obligations SET status='submitted', latest_submission_id=? WHERE id=?", [sid, oid]);
    await audit(tx, c, { module: "activities", action: "submitted", entityType: "obligation", entityId: oid, providerId: o["provider_id"], summary: `${o["dname"]} submitted (version ${v})`, after: { files: u.files.map((f) => f.name), checklist } });
  });
  return get(c, oid);
}
export async function review(c: Ctx, oid: string, b: { decision: "approve" | "return"; items: Record<string, { ok: boolean; comment?: string | undefined }>; note?: string | undefined; newDueDate?: string | undefined }) {
  const o = await row(c, oid);
  if (b.decision === "return" && !b.note?.trim() && !Object.values(b.items).some((i) => !i.ok && i.comment?.trim())) invalid("note", "Explain what must be corrected.");
  if (b.decision === "approve" && Object.values(b.items).some((i) => !i.ok)) invalid("items", "An item is marked not OK, so this cannot be approved.");
  if (b.newDueDate && b.newDueDate < today()) invalid("newDueDate", "The new due date is in the past.");
  await transaction(async (tx) => {
    const done = await execute(tx, "UPDATE activity_submissions SET status=?, reviewed_by=?, reviewed_at=UTC_TIMESTAMP(3), review_json=?, review_note=? WHERE id=? AND status='submitted'", [b.decision === "approve" ? "approved" : "returned", c.user.id, JSON.stringify(b.items), b.note ?? null, o["latest_submission_id"] ?? "0"]);
    if (!done.affectedRows) conflict("NOTHING_TO_REVIEW", "There is no submission waiting for review.");
    await execute(tx, "UPDATE activity_obligations SET status=?, due_date=COALESCE(?,due_date), close_date=GREATEST(close_date, COALESCE(?,close_date)) WHERE id=?", [b.decision === "approve" ? "approved" : "returned", b.newDueDate ?? null, b.newDueDate ?? null, oid]);
    await queueKpis(tx, c.pid);
    await audit(tx, c, { module: "activities", action: b.decision === "approve" ? "approved" : "returned", entityType: "obligation", entityId: oid, providerId: o["provider_id"], summary: `${o["dname"]} ${b.decision === "approve" ? "approved" : "returned"}`, after: b });
  });
  return get(c, oid);
}
export async function extend(c: Ctx, oid: string, closeDate: string, note: string) {
  const o = await row(c, oid);
  if (closeDate <= o["close_date"] || closeDate < today()) invalid("closeDate", "Choose a later date.");
  await transaction(async (tx) => {
    await execute(tx, "UPDATE activity_obligations SET close_date=?, due_date=?, status=IF(status='overdue','open',status) WHERE id=? AND status NOT IN ('approved','waived')", [closeDate, closeDate, oid]);
    await insert(tx, "activity_obligation_notes", { obligation_id: oid, kind: "extended", note, actor_user_id: c.user.id });
    await audit(tx, c, { module: "activities", action: "extended", entityType: "obligation", entityId: oid, providerId: o["provider_id"], summary: `${o["dname"]} extended to ${closeDate}`, before: { due: o["due_date"], close: o["close_date"] }, after: { closeDate, note } });
  });
  return get(c, oid);
}
export async function reviewQueue(c: Ctx) {
  const s = S(c);
  return (await query(pool, `${SEL.replace("SELECT o.*", "SELECT o.*, x.submitted_at, x.version_no, x.is_late")} JOIN activity_submissions x ON x.id=o.latest_submission_id WHERE o.project_id=? AND o.status='submitted' AND ${s.sql} ORDER BY x.submitted_at`, [c.pid, ...s.args] as never[])).map((o) => ({ ...view(o), submittedAt: o["submitted_at"], version: o["version_no"], isLate: Boolean(o["is_late"]) }));
}
const scheduleView = (s: Row) => ({ id: s["id"], appliesTo: s["pcode"] ?? (s["months"] ? `${s["months"]} months` : s["applies_level"] ?? "all"), anchor: s["anchor"], openOffset: s["open_offset_days"], dueOffset: s["due_offset_days"], graceDays: s["grace_days"], repeatEvery: s["repeat_every_days"] ?? undefined, repeatCount: s["repeat_count"] ?? undefined, breakdownExtends: Boolean(s["breakdown_extends"]), active: Boolean(s["is_active"]), ...(s["legacy_rule_json"] ? { legacy: true } : {}) });
export async function definitions(c: Ctx) {
  const sch = await query(pool, "SELECT s.*, p.code AS pcode, d.months FROM activity_schedules s LEFT JOIN providers p ON p.id=s.applies_provider_id LEFT JOIN durations d ON d.id=s.applies_duration_id ORDER BY s.id");
  return (await query(pool, "SELECT * FROM activity_definitions WHERE project_id=? ORDER BY sort_order, id", [c.pid])).map((d) => ({ id: d["id"], code: d["code"], name: d["name"], description: d["description"] ?? "", scope: d["scope"], linkedIndicator: d["linked_indicator_code"] ?? undefined, recurrence: d["recurrence"], active: Boolean(d["is_active"]), evidence: rules(d["evidence_rules_json"]), schedules: sch.filter((s) => s["definition_id"] === d["id"]).map(scheduleView) }));
}
export async function saveDefinition(c: Ctx, did: string | null, b: Row) {
  const cols: Record<string, SqlValue | undefined> = { code: b["code"], name: b["name"], description: b["description"], scope: b["scope"], linked_indicator_code: b["linkedIndicator"], recurrence: b["recurrence"], is_active: b["active"], evidence_rules_json: b["evidence"] ? JSON.stringify(b["evidence"]) : undefined };
  if (did && !(await one(pool, "SELECT 1 AS x FROM activity_definitions WHERE id=? AND project_id=?", [did, c.pid]))) notFound("Activity");
  if (did && b["scope"] && (await one(pool, "SELECT 1 AS x FROM activity_definitions d JOIN activity_obligations o ON o.definition_id=d.id WHERE d.id=? AND d.scope<>? LIMIT 1", [did, b["scope"]]))) invalid("scope", "The scope cannot change once obligations exist.");
  const id = await transaction(async (tx) => {
    const x = did ?? (await insert(tx, "activity_definitions", { project_id: c.pid, sort_order: 99, ...cols }));
    if (did) await update(tx, "activity_definitions", did, cols);
    if (Array.isArray(b["providerIds"])) { await execute(tx, "DELETE FROM activity_assignments WHERE definition_id=?", [x]); for (const p of b["providerIds"] as string[]) { if (!(await one(tx, "SELECT 1 AS x FROM providers WHERE id=? AND project_id=?", [p, c.pid]))) invalid("providerIds", "Choose providers of this project."); await insert(tx, "activity_assignments", { definition_id: x, provider_id: p }); } }
    await materialize(tx, c.pid);
    await audit(tx, c, { module: "activities", action: "definition_saved", entityType: "activity", entityId: x, summary: `Activity ${b["name"] ?? x} saved`, after: b });
    return x;
  });
  return (await definitions(c)).find((d) => d.id === id);
}
export async function saveSchedule(c: Ctx, did: string, b: Row) {
  if (!(await one(pool, "SELECT 1 AS x FROM activity_definitions WHERE id=? AND project_id=?", [did, c.pid]))) notFound("Activity");
  const to = String(b["appliesTo"] ?? "all"), level = ["basic", "intermediate", "advanced"].includes(to) ? to : null, dur = /^(\d+) months$/.exec(to), provider = level || dur || to === "all" ? null : ((await one(pool, "SELECT id FROM providers WHERE project_id=? AND code=?", [c.pid, to])) ?? invalid("appliesTo", "Choose who this applies to."));
  const durId = dur ? ((await one(pool, "SELECT id FROM durations WHERE months=?", [dur[1]!])) ?? invalid("appliesTo", "Choose a duration."))["id"] : null;
  if (b["dueOffset"] < b["openOffset"]) invalid("dueOffset", "The due day must be on or after the opening day.");
  const cols: Record<string, SqlValue> = { definition_id: did, applies_level: level, applies_duration_id: durId, applies_provider_id: provider?.["id"] ?? null, anchor: b["anchor"], open_offset_days: b["openOffset"], due_offset_days: b["dueOffset"], grace_days: b["graceDays"], repeat_every_days: b["repeatEvery"] ?? null, repeat_count: b["repeatCount"] ?? 1, breakdown_extends: b["breakdownExtends"], is_active: b["active"] };
  const sid = await transaction(async (tx) => {
    const old = b["id"] ? ((await one(tx, "SELECT * FROM activity_schedules WHERE id=? AND definition_id=?", [b["id"], did])) ?? notFound("Schedule")) : undefined;
    if (old?.["legacy_rule_json"] && b["active"]) conflict("LEGACY_SCHEDULE", "This schedule came from the old system and is kept for the record. Create a new one.");
    const id = old ? String(old["id"]) : await insert(tx, "activity_schedules", { ...cols, schedule_version: 1 });
    if (old) await update(tx, "activity_schedules", id, { ...cols, schedule_version: old["schedule_version"] + 1 });
    await materialize(tx, c.pid);
    await audit(tx, c, { module: "activities", action: "schedule_saved", entityType: "schedule", entityId: id, summary: "Activity schedule saved", before: old, after: b });
    return id;
  });
  return (await definitions(c)).flatMap((d) => d.schedules).find((s) => s.id === sid);
}
export async function preview(c: Ctx) {
  const providerId = c.query["providerId"] ?? "", p = (await one(pool, "SELECT * FROM providers WHERE id=? AND project_id=?", [providerId, c.pid])) ?? notFound("Provider"), defs = new Map((await query(pool, "SELECT * FROM activity_definitions WHERE project_id=?", [c.pid])).map((d) => [String(d["id"]), d])), old = await query(pool, "SELECT * FROM activity_obligations WHERE provider_id=?", [providerId]);
  if (c.access.providerId && c.access.providerId !== providerId) deny();
  const names = new Map((await query(pool, "SELECT CONCAT('class:',id) AS k, code AS n FROM training_classes WHERE provider_id=? UNION ALL SELECT CONCAT('site:',id), display_name FROM training_sites WHERE provider_id=? UNION ALL SELECT CONCAT('training:',id), title FROM trainings WHERE provider_id=?", [providerId, providerId, providerId])).map((x) => [x["k"] as string, x["n"] as string]));
  return (await plan(pool, c.pid, providerId)).map((x, i) => { const o = old.find((y) => y["definition_id"] === x.definitionId && y["scope_key"] === x.scopeKey && y["sequence_no"] === x.seq), d = defs.get(x.definitionId)!; return { id: o ? o["id"] : `new-${i}`, providerId, providerCode: p["code"], activity: { code: d["code"], name: d["name"], scope: d["scope"] }, scopeLabel: names.get(x.scopeKey) ?? p["name"], openDate: x.open, dueDate: x.due, closeDate: x.close, status: o?.["status"] ?? "upcoming", change: !o ? "new" : o["due_date"] !== x.due || o["open_date"] !== x.open ? "moved" : "unchanged" }; });
}
export async function compliance(c: Ctx) {
  const defs = await query(pool, "SELECT id, code, name, scope FROM activity_definitions WHERE project_id=? AND is_active=1 ORDER BY sort_order, id", [c.pid]), s = scope(c, { provider: "p.id" }), providers = await query(pool, `SELECT p.id, p.code FROM providers p WHERE p.project_id=? AND ${s.sql} ORDER BY p.code`, [c.pid, ...s.args] as never[]), os = await query(pool, "SELECT provider_id, definition_id, status, COUNT(*) AS n FROM activity_obligations WHERE project_id=? AND status<>'waived' GROUP BY 1,2,3", [c.pid]);
  return { activities: defs.map((d) => ({ code: d["code"], name: d["name"], scope: d["scope"] })), rows: providers.map((p) => ({ providerId: p["id"], providerCode: p["code"], cells: defs.map((d) => { const mine = os.filter((o) => o["provider_id"] === p["id"] && o["definition_id"] === d["id"]), n = (k: string) => mine.find((m) => m["status"] === k)?.["n"] ?? 0, total = mine.reduce((a, m) => a + m["n"], 0); return { code: d["code"], approved: n("approved"), total, status: !total ? "none" : n("overdue") ? "overdue" : n("returned") ? "returned" : n("submitted") ? "submitted" : n("approved") === total ? "approved" : n("open") ? "open" : "upcoming" }; }) })) };
}
export async function file(c: Ctx, oid: string, fid: string) { await row(c, oid); if (!(await one(pool, "SELECT 1 AS x FROM activity_submission_files f JOIN activity_submissions s ON s.id=f.submission_id WHERE s.obligation_id=? AND f.file_id=?", [oid, fid]))) notFound("File"); return openFile(fid); }
/** A new provider takes part in every programme activity. Activities a provider defined for itself stay its own. */
export const assignProvider = (db: Db, pid: string, providerId: string) => execute(db, "INSERT IGNORE INTO activity_assignments (definition_id, provider_id) SELECT id, ? FROM activity_definitions WHERE project_id=? AND is_active=1 AND created_by_provider_id IS NULL", [providerId, pid]);
export const reviewer = (c: Ctx) => can(c, "activity.review");
void DomainError;
