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 { classInScope, conflict, invalid, notFound, scope, type Ctx } from "../../core/http/route.js";
import { defineJob } from "../../core/jobs/jobs.js";
import { sha256 } from "../../core/crypto.js";
import { today } from "../../shared/dates.js";
import { allClasses, getClassView } from "../delivery/index.js";
import { enumLookup } from "./lookup.js";
import * as reg from "./registration.service.js";
import { checkTrainee } from "./trainee.rules.js";

export async function snapshot(db: Db, classId: string, kind: "freeze" | "manual", userId: string | null): Promise<string> {
  const m = await query(db, "SELECT id, roster_status AS s FROM trainees WHERE class_id=? AND roster_status IN ('active','reserve') ORDER BY id", [classId]);
  const sid = await insert(db, "roster_snapshots", { class_id: classId, kind, members_count: m.length, members_hash: sha256(m.map((x) => `${x["id"]}:${x["s"]}`).join(",")), taken_by: userId });
  await insertMany(db, "roster_snapshot_members", ["snapshot_id", "trainee_id", "roster_status"], m.map((x) => [sid, x["id"], x["s"]]));
  return sid;
}
export const snapshots = async (classId: string) => (await query(pool, "SELECT id, taken_at AS takenAt, kind, members_count AS members FROM roster_snapshots WHERE class_id=? ORDER BY id DESC", [classId]));
/** V1 registration integrity: what changed since a snapshot. */
export async function diff(c: Ctx, classId: string, snapshotId: string) {
  await classInScope(c, classId);
  const old = await query(pool, "SELECT m.trainee_id AS id, m.roster_status AS s FROM roster_snapshot_members m JOIN roster_snapshots r ON r.id=m.snapshot_id WHERE r.id=? AND r.class_id=?", [snapshotId, classId]);
  const now = await query(pool, "SELECT id, roster_status AS s FROM trainees WHERE class_id=? AND roster_status IN ('active','reserve')", [classId]), before = new Map(old.map((o) => [String(o["id"]), o["s"]])), after = new Map(now.map((o) => [String(o["id"]), o["s"]]));
  const list = async (ids: string[]) => (ids.length ? reg.traineeRows(c, "t.id IN (?)", [ids]) : []);
  return { added: await list([...after.keys()].filter((i) => !before.has(i))), removed: await list([...before.keys()].filter((i) => !after.has(i))), changed: await list([...after.keys()].filter((i) => before.has(i) && before.get(i) !== after.get(i))) };
}
export async function classDetail(c: Ctx, classId: string) {
  const { calendarDays } = await import("../delivery/index.js"), { classOutcomes } = await import("../outcomes/index.js"), { obligationsOfClass } = await import("../activities/index.js");
  const cls = await getClassView(c, classId);
  return { cls, calendar: await calendarDays(classId), roster: await reg.traineeRows(c, "t.class_id=?", [classId]), outcomes: await classOutcomes(classId), obligations: await obligationsOfClass(c, classId), snapshots: await snapshots(classId) };
}
/** V1 roster insights: how many trainees each class has. Active and reserve are equal everywhere. */
export async function insights(c: Ctx) {
  const classes = await allClasses(c), counts = await query(pool, "SELECT class_id, SUM(roster_status='active') AS active, SUM(roster_status='reserve') AS reserve FROM trainees WHERE project_id=? GROUP BY class_id", [c.pid]);
  return { rows: classes.map((k) => { const n = counts.find((x) => x["class_id"] === k.id) ?? {}; return { classId: k.id, classCode: k.code, providerCode: k.providerCode, active: n["active"] ?? 0, reserve: n["reserve"] ?? 0, rosterFrozenAt: k.rosterFrozenAt }; }) };
}
/** When the window of a class closes, its list is kept as a snapshot that later checks compare with. */
defineJob("roster.autoFreeze", async (job) => {
  const rows = await query(pool, "SELECT c.id, c.code, c.provider_id FROM training_classes c JOIN projects p ON p.id=c.project_id JOIN providers v ON v.id=c.provider_id WHERE c.project_id=? AND c.roster_frozen_at IS NULL AND c.is_cancelled=0 AND COALESCE(c.actual_start,c.planned_start)+INTERVAL p.roster_freeze_offset_days DAY<? AND (v.registration_late_until IS NULL OR v.registration_late_until<?)", [job.projectId!, today(), today()]);
  for (const k of rows) await transaction(async (tx) => { await execute(tx, "UPDATE training_classes SET roster_frozen_at=UTC_TIMESTAMP(3) WHERE id=?", [k["id"]]); await snapshot(tx, k["id"], "freeze", null); });
  return { message: `${rows.length} class lists were kept.` };
});
