import { audit } from "../../core/audit/audit.js";
import { execute, insert, json, one, pool, query, transaction, update, type Db, type Row } from "../../core/db/db.js";
import { enqueue } from "../../core/jobs/jobs.js";
import { invalid, notFound, type Ctx } from "../../core/http/route.js";

export async function listProjects(c: Ctx) {
  return (await query(pool, `SELECT p.id, p.code, p.title, p.donor, p.sector, p.location_text AS location, p.description, p.start_date AS start, p.end_date AS end, r.code AS roleCode, r.label AS roleLabel, t.name AS providerName, (SELECT COUNT(*) FROM trainees x WHERE x.project_id=p.id AND x.roster_status IN ('active','reserve') AND (m.provider_id IS NULL OR x.provider_id=m.provider_id)) AS trainees,
    (SELECT COUNT(*) FROM providers x WHERE x.project_id=p.id AND (m.provider_id IS NULL OR x.id=m.provider_id)) AS providers FROM memberships m JOIN projects p ON p.id=m.project_id JOIN roles r ON r.id=m.role_id LEFT JOIN providers t ON t.id=m.provider_id WHERE m.user_id=? AND m.status='active' ORDER BY p.id`, [c.user.id]))
    .map((p) => ({ ...p, providerName: p["providerName"] ?? undefined }));
}
const appSetting = async <T>(key: string, fallback: T): Promise<T> => json<T>((await one(pool, "SELECT value_json AS v FROM app_settings WHERE setting_key=?", [key]))?.["v"], fallback);
export async function getSettings(pid: string) {
  const p = (await one(pool, "SELECT * FROM projects WHERE id=?", [pid])) ?? notFound("Project");
  return { id: p["id"], code: p["code"], title: p["title"], donor: p["donor"] ?? "", sector: p["sector"] ?? "", location: p["location_text"] ?? "", description: p["description"] ?? "", start: p["start_date"] ?? "", end: p["end_date"] ?? "", overEnrolmentPct: Number(p["over_enrolment_pct"]), attendanceThreshold: Number(p["attendance_threshold_pct"]), exemptDays: p["exempt_days_from_class_start"],
    lateDays: p["late_attendance_days"], lateApproval: Boolean(p["late_attendance_approval"]), grievanceSlaDays: p["grievance_sla_days"], rosterFreezeOffset: p["roster_freeze_offset_days"], registrationOpen: !p["registration_closed_at"], registrationCloseNote: p["registration_close_note"] ?? undefined, registrationClosedAt: p["registration_closed_at"] ?? undefined, registrationClosedBy: p["registration_closed_by"] ? (await one(pool, "SELECT name FROM users WHERE id=?", [p["registration_closed_by"]]))?.["name"] : undefined,
    remindersOn: await appSetting<boolean>("reminders.enabled", true),
    require2faRoles: await appSetting<string[]>("security.require_2fa_roles", []), enforce2fa: await appSetting<boolean>("security.enforce_2fa", false) };
}
const COLUMNS: Record<string, string> = { title: "title", donor: "donor", sector: "sector", location: "location_text", description: "description", start: "start_date", end: "end_date", overEnrolmentPct: "over_enrolment_pct", attendanceThreshold: "attendance_threshold_pct", exemptDays: "exempt_days_from_class_start", lateDays: "late_attendance_days", lateApproval: "late_attendance_approval", grievanceSlaDays: "grievance_sla_days", rosterFreezeOffset: "roster_freeze_offset_days" };
export async function saveSettings(c: Ctx, b: Row) {
  const before = await getSettings(c.pid);
  if (b["start"] && b["end"] && b["end"] < b["start"]) invalid("end", "The end date is before the start date.");
  await transaction(async (tx) => {
    await update(tx, "projects", c.pid, Object.fromEntries(Object.entries(COLUMNS).filter(([k]) => b[k] !== undefined).map(([k, col]) => [col, b[k]])));
    if (b["registrationOpen"] !== undefined) await execute(tx, "UPDATE projects SET registration_closed_at=IF(?,NULL,COALESCE(registration_closed_at,UTC_TIMESTAMP(3))), registration_closed_by=IF(?,NULL,?), registration_close_note=? WHERE id=?", [b["registrationOpen"], b["registrationOpen"], c.user.id, b["registrationCloseNote"] ?? null, c.pid]);
    for (const [k, key] of [["require2faRoles", "security.require_2fa_roles"], ["enforce2fa", "security.enforce_2fa"], ["remindersOn", "reminders.enabled"]] as const) if (b[k] !== undefined) await execute(tx, "INSERT INTO app_settings (setting_key, value_json, updated_by) VALUES (?,?,?) ON DUPLICATE KEY UPDATE value_json=VALUES(value_json), updated_by=VALUES(updated_by)", [key, JSON.stringify(b[k]), c.user.id]);
    await audit(tx, c, { module: "projects", action: "settings_changed", entityType: "project", entityId: c.pid, summary: "Project settings changed", before, after: b });
    if (b["exemptDays"] !== undefined && b["exemptDays"] !== before.exemptDays) await enqueue(tx, "attendance.recomputeAll", {}, { projectId: c.pid, userId: c.user.id, dedupe: `recompute:${c.pid}` });
  });
  return getSettings(c.pid);
}
/** Which tables describe how a project works. They can be copied into a new one; people and results never are. */
const SETUP: Record<string, string[]> = {
  indicator_definitions: ["code", "version_no", "status", "protocol_no", "name", "unit", "level", "purpose", "operational_definition", "data_sources", "frequency", "computation_text", "numerator_metric", "denominator_metric", "direction", "default_target", "comparator", "verification_method", "display_order"],
  indicator_stages: ["indicator_code", "stage_key", "label", "offset_days", "is_final", "sort_order", "is_active"],
  holidays: ["holiday_date", "label", "location_id", "kind"],
};
export async function createProject(c: Ctx, b: Row) {
  if (await one(pool, "SELECT 1 AS x FROM projects WHERE code=?", [b["code"]])) invalid("code", "Another project uses this code.");
  if (b["start"] && b["end"] && b["end"] <= b["start"]) invalid("end", "The end date must be after the start date.");
  const from = b["copyFrom"] ? await one(pool, "SELECT p.* FROM projects p JOIN memberships m ON m.project_id=p.id AND m.user_id=? AND m.status='active' JOIN roles r ON r.id=m.role_id AND r.code='system_admin' WHERE p.id=?", [c.user.id, b["copyFrom"]]) : undefined;
  if (b["copyFrom"] && !from) invalid("copyFrom", "Choose one of your projects.");
  const pid = await transaction(async (tx) => {
    const policy = Object.fromEntries(["over_enrolment_pct", "attendance_threshold_pct", "exempt_days_from_class_start", "late_attendance_days", "late_attendance_approval", "grievance_sla_days", "roster_freeze_offset_days"].filter(() => from).map((k) => [k, from![k]]));
    const id = await insert(tx, "projects", { code: b["code"], title: b["title"], donor: b["donor"], sector: b["sector"], location_text: b["location"], description: b["description"], start_date: b["start"], end_date: b["end"], ...policy });
    const role = (await one(tx, "SELECT id FROM roles WHERE code='system_admin'"))!;
    await insert(tx, "memberships", { project_id: id, user_id: c.user.id, role_id: role["id"], status: "active" });
    // The official indicators always come along: a project without them has nothing to measure.
    const source = from?.["id"] ?? (await one(tx, "SELECT MIN(id) AS id FROM projects"))!["id"];
    for (const [t, cols] of Object.entries(SETUP)) if (from || t === "indicator_definitions") await execute(tx, `INSERT INTO ${t} (project_id, ${cols.join(", ")}) SELECT ?, ${cols.map((k) => (t === "indicator_definitions" && k === "version_no" ? "1" : k)).join(", ")} FROM ${t} WHERE project_id=? ${t === "indicator_definitions" ? "AND status='active'" : ""}`, [id, source]);
    if (from) for (const d of await query(tx, "SELECT * FROM activity_definitions WHERE project_id=? AND created_by_provider_id IS NULL", [source])) {
      const nid = await insert(tx, "activity_definitions", { project_id: id, code: d["code"], name: d["name"], description: d["description"], scope: d["scope"], linked_indicator_code: d["linked_indicator_code"], recurrence: d["recurrence"], evidence_rules_json: d["evidence_rules_json"] === null || typeof d["evidence_rules_json"] === "string" ? d["evidence_rules_json"] : JSON.stringify(d["evidence_rules_json"]), sort_order: d["sort_order"], is_active: d["is_active"] });
      for (const x of await query(tx, "SELECT * FROM activity_schedules WHERE definition_id=? AND applies_provider_id IS NULL AND is_active=1", [d["id"]])) { const { id: _id, definition_id: _d, created_at: _c, updated_at: _u, ...rest } = x as Row; await insert(tx, "activity_schedules", { ...rest, definition_id: nid } as never); }
    }
    if (from) await execute(tx, "INSERT IGNORE INTO reminder_rules (project_id, rule_key, is_enabled, offsets_json, repeat_after_days, severity, email_enabled, config_json) SELECT ?, rule_key, is_enabled, offsets_json, repeat_after_days, severity, email_enabled, config_json FROM reminder_rules WHERE project_id=?", [id, source]);
    await audit(tx, { ...c, pid: id }, { module: "projects", action: "project_created", entityType: "project", entityId: id, summary: `Created project ${b["code"]}`, after: b });
    await queueKpis(tx, id);
    return id;
  });
  return { id: pid, code: b["code"], title: b["title"] };
}
export const listHolidays = async (pid: string) => (await query(pool, "SELECT h.id, h.holiday_date AS date, h.label, h.kind, l.code AS locationCode FROM holidays h LEFT JOIN locations l ON l.id=h.location_id WHERE h.project_id=? ORDER BY h.holiday_date", [pid])).map((h) => ({ ...h, locationCode: h["locationCode"] ?? undefined }));
export async function addHoliday(c: Ctx, b: { date: string; label: string; kind: string; locationCode?: string | undefined; reason?: string | undefined }) {
  const loc = b.locationCode ? ((await one(pool, "SELECT id FROM locations WHERE code=?", [b.locationCode])) ?? invalid("locationCode", "Choose a location.")) : undefined;
  if (await one(pool, "SELECT 1 AS x FROM holidays WHERE project_id=? AND holiday_date=? AND (location_id <=> ?)", [c.pid, b.date, loc?.["id"] ?? null])) invalid("date", "This date is already a holiday.");
  const impact = (await one(pool, "SELECT COUNT(DISTINCT s.class_id) AS classes, COALESCE(SUM(s.marks_count),0) AS marks FROM attendance_sessions s WHERE s.project_id=? AND s.session_date=?", [c.pid, b.date]))!;
  const hid = await transaction(async (tx) => {
    const id = await insert(tx, "holidays", { project_id: c.pid, holiday_date: b.date, label: b.label, kind: b.kind, location_id: loc?.["id"], created_by: c.user.id });
    await audit(tx, c, { module: "projects", action: "holiday_added", entityType: "holiday", entityId: id, summary: `Holiday ${b.date} ${b.label}`, after: b });
    await enqueue(tx, "attendance.recomputeAll", {}, { projectId: c.pid, userId: c.user.id, dedupe: `recompute:${c.pid}` });
    return id;
  });
  return { id: hid, date: b.date, label: b.label, kind: b.kind, ...(b.locationCode ? { locationCode: b.locationCode } : {}), impact };
}
export async function removeHoliday(c: Ctx, hid: string) {
  const h = (await one(pool, "SELECT * FROM holidays WHERE id=? AND project_id=?", [hid, c.pid])) ?? notFound("Holiday");
  await transaction(async (tx) => {
    await execute(tx, "DELETE FROM holidays WHERE id=?", [hid]);
    await audit(tx, c, { module: "projects", action: "holiday_removed", entityType: "holiday", entityId: hid, summary: `Removed holiday ${h["holiday_date"]}`, before: h });
    await enqueue(tx, "attendance.recomputeAll", {}, { projectId: c.pid, userId: c.user.id, dedupe: `recompute:${c.pid}` });
  });
}
export const listLocations = async () => (await query(pool, "SELECT id, code, name, region_code AS regionCode, is_active AS active FROM locations ORDER BY name")).map((l) => ({ ...l, regionCode: l["regionCode"] ?? "", active: Boolean(l["active"]) }));
export async function saveLocation(c: Ctx, b: { id?: string | undefined; code: string; name: string; regionCode?: string | undefined; active?: boolean | undefined }) {
  if (await one(pool, "SELECT 1 AS x FROM locations WHERE code=? AND id<>?", [b.code, b.id ?? "0"])) invalid("code", "Another location uses this code.");
  const row = { code: b.code, name: b.name, region_code: b.regionCode || null, is_active: b.active ?? true };
  const lid = b.id ?? (await insert(pool, "locations", row));
  if (b.id && !(await one(pool, "SELECT 1 AS x FROM locations WHERE id=?", [b.id]))) notFound("Location");
  if (b.id) await update(pool, "locations", b.id, row);
  await audit(pool, c, { module: "projects", action: "location_saved", entityType: "location", entityId: lid, summary: `Saved location ${b.name}`, after: b });
  return (await listLocations()).find((l) => (l as Row)["id"] === lid);
}
export const listDurations = () => query(pool, "SELECT id, months, label, sort_order AS sortOrder, is_active AS active FROM durations ORDER BY sort_order, months");
export async function saveDuration(c: Ctx, b: { id?: string | undefined; months: number; label: string; active?: boolean | undefined }) {
  const row = { months: b.months, label: b.label, is_active: b.active ?? true };
  const did = b.id ?? (await insert(pool, "durations", row));
  if (b.id) await update(pool, "durations", b.id, row);
  await audit(pool, c, { module: "projects", action: "duration_saved", entityType: "duration", entityId: did, summary: `Saved duration ${b.label}`, after: b });
  return (await listDurations()).find((d) => d["id"] === did);
}
export async function listRegions() {
  return { regions: await query(pool, "SELECT code, name FROM regions WHERE is_active=1 ORDER BY sort_order, name"), aliases: await query(pool, "SELECT alias_norm AS alias, canonical FROM enum_aliases WHERE domain='region' ORDER BY alias_norm") };
}
export const norm = (s: string) => s.toLowerCase().replace(/[’]/g, "'").replace(/[–—]/g, "-").replace(/[^\p{L}\p{N}]+/gu, " ").trim();
export async function addAlias(c: Ctx, b: { alias: string; canonical: string }) {
  if (!(await one(pool, "SELECT 1 AS x FROM regions WHERE code=?", [b.canonical]))) invalid("canonical", "Choose a region.");
  await transaction(async (tx) => {
    await execute(tx, "INSERT INTO enum_aliases (domain, alias_norm, canonical) VALUES ('region',?,?) ON DUPLICATE KEY UPDATE canonical=VALUES(canonical)", [norm(b.alias), b.canonical]);
    await audit(tx, c, { module: "projects", action: "region_alias", summary: `Region spelling ${b.alias} means ${b.canonical}`, after: b });
  });
  return { alias: norm(b.alias), canonical: b.canonical };
}
export const queueKpis = (db: Db, pid: string) => enqueue(db, "kpi.recompute", {}, { projectId: pid, delaySeconds: 5, dedupe: `kpi:${pid}` });
