import { audit } from "../../core/audit/audit.js";
import { execute, insert, json, one, pool, query, transaction, update, type Row } from "../../core/db/db.js";
import { conflict, invalid, like, notFound, paging, sameProvider, scope, type Ctx } from "../../core/http/route.js";
import { enqueue } from "../../core/jobs/jobs.js";
import { addDays, today } from "../../shared/dates.js";
import { parsePhone } from "../../shared/phone.js";
import { invite, listMembers } from "../access/index.js";
import { assignProvider, materialize } from "../activities/index.js";
import { allClasses, listTrainings, rate } from "../delivery/index.js";
import { cards, definitions } from "../indicators/index.js";
import { getSettings, queueKpis } from "../projects/index.js";
import { maxRegistration, providerRules } from "../registration/index.js";

const opt = <T>(v: T | null | undefined) => v ?? undefined;
async function views(c: Ctx, rows: Row[]) {
  if (!rows.length) return [];
  const ids = rows.map((r) => r["id"] as string), classes = await allClasses(c);
  const st = await query(pool, "SELECT c.provider_id AS p, SUM(k.active_count) AS a, SUM(k.reserve_count) AS r, SUM(k.att_present) AS n, SUM(k.att_possible) AS d, SUM(k.completed) AS done, SUM(k.tracked_trainees) AS t FROM training_classes c JOIN class_counters k ON k.class_id=c.id WHERE c.provider_id IN (?) GROUP BY c.provider_id", [ids]);
  const ob = await query(pool, "SELECT provider_id AS p, SUM(status IN ('open','returned','overdue')) AS o, SUM(status='overdue') AS v FROM activity_obligations WHERE provider_id IN (?) GROUP BY provider_id", [ids]), gr = await query(pool, "SELECT provider_id AS p, SUM(status NOT IN ('resolved','closed','responded')) AS o FROM grievance_cases WHERE provider_id IN (?) GROUP BY provider_id", [ids]), df = await query(pool, "SELECT provider_id AS p, SUM(severity='error') AS e, SUM(severity='warning') AS w FROM datahealth_findings WHERE provider_id IN (?) AND resolved_at IS NULL GROUP BY provider_id", [ids]), loc = await query(pool, "SELECT DISTINCT s.provider_id AS p, l.code FROM training_sites s JOIN locations l ON l.id=s.location_id WHERE s.provider_id IN (?)", [ids]), lev = await query(pool, "SELECT DISTINCT provider_id AS p, level FROM trainings WHERE provider_id IN (?)", [ids]);
  const out = [];
  for (const p of rows) {
    const id = p["id"], of = (x: Row[]) => x.find((r) => String(r["p"]) === String(id)) ?? {}, s = of(st), k = await providerRules(pool, id), mine = classes.filter((x) => x.providerId === id), contract = await one(pool, "SELECT levels_json FROM provider_contracts WHERE provider_id=? ORDER BY status='active' DESC, id DESC LIMIT 1", [id]), codes = json<{ levels?: string[]; locationCodes?: string[] }>(contract?.["levels_json"], {});
    out.push({ id, code: p["code"], name: p["name"], legalName: opt(p["legal_name"]), status: p["status"], contactName: opt(p["contact_name"]), contactPhone: opt(p["contact_phone_raw"]), contactEmail: opt(p["contact_email"]), contractTarget: k["target"], registered: k["registered"], activeCount: s["a"] ?? 0, reserveCount: s["r"] ?? 0, maxRegistration: maxRegistration(k["target"], k["pct"]), levels: [...new Set([...lev.filter((x) => String(x["p"]) === String(id)).map((x) => x["level"]), ...(codes.levels ?? [])])], locationCodes: [...new Set([...loc.filter((x) => String(x["p"]) === String(id)).map((x) => x["code"]), ...(codes.locationCodes ?? [])])], notificationEmail: opt(p["notification_email"]), replyToEmail: opt(p["reply_to_email"]), requiresExternalId: Boolean(p["requires_external_id"]), externalIdLabel: opt(p["external_id_label"]), registrationWindow: { from: opt(p["registration_open_from"]), until: opt(p["registration_open_until"]), closedAt: opt(p["registration_closed_at"]), closeNote: opt(p["registration_close_note"]), lateUntil: opt(p["registration_late_until"]) }, projectRegistrationOpen: !k["project_closed"], registrationOpen: p["status"] === "active" && !p["registration_closed_at"] && !k["project_closed"] && mine.some((x) => x.registrationOpen),
      attendanceRate: rate(s["n"], s["d"]), completionRate: rate(s["done"], s["t"]), openObligations: Number(of(ob)["o"] ?? 0), overdueObligations: Number(of(ob)["v"] ?? 0), openGrievances: Number(of(gr)["o"] ?? 0), classesOngoing: mine.filter((x) => x.status === "ongoing").length, classesEnded: mine.filter((x) => x.status === "ended").length, dataHealth: Math.max(0, 100 - Number(of(df)["e"] ?? 0) * 10 - Math.min(40, Number(of(df)["w"] ?? 0) * 2)), version: p["version"] });
  }
  return out;
}
export async function list(c: Ctx) {
  const s = scope(c, { provider: "p.id" }), q = c.query, pg = paging(q), where = ["p.project_id=?", s.sql], args: unknown[] = [c.pid, ...s.args];
  if (q["status"]) { where.push("p.status=?"); args.push(q["status"]); }
  if (q["q"]) { where.push("(p.code LIKE ? OR p.name LIKE ?)"); args.push(like(q["q"]), like(q["q"])); }
  const w = where.join(" AND ");
  return { items: await views(c, await query(pool, `SELECT p.* FROM providers p WHERE ${w} ORDER BY p.code LIMIT ? OFFSET ?`, [...args, pg.pageSize, pg.offset] as never[])), page: pg.page, pageSize: pg.pageSize, total: (await one(pool, `SELECT COUNT(*) AS n FROM providers p WHERE ${w}`, args as never[]))!["n"] };
}
async function row(c: Ctx, pid: string): Promise<Row> { const p = (await one(pool, "SELECT * FROM providers WHERE id=? AND project_id=?", [pid, c.pid])) ?? notFound("Provider"); sameProvider(c, pid); return p; }
export const view = async (c: Ctx, pid: string) => (await views(c, [await row(c, pid)]))[0]!;
export async function get(c: Ctx, pid: string) {
  const provider = await view(c, pid), k = await query(pool, "SELECT * FROM provider_contracts WHERE provider_id=? ORDER BY id", [pid]), cur = k.find((x) => x["status"] === "active") ?? k.at(-1), defs = await definitions(c.pid), own = await query(pool, "SELECT indicator_code AS c, target_value AS v FROM indicator_targets WHERE provider_id=? AND effective_from<=CURRENT_DATE AND (effective_to IS NULL OR effective_to>=CURRENT_DATE) ORDER BY effective_from", [pid]);
  const ob = await query(pool, "SELECT o.id, o.status, o.open_date, o.due_date, o.close_date, d.code, d.name, d.scope, k.code AS kc, t.title FROM activity_obligations o JOIN activity_definitions d ON d.id=o.definition_id LEFT JOIN training_classes k ON k.id=o.class_id LEFT JOIN trainings t ON t.id=o.training_id WHERE o.provider_id=? ORDER BY o.due_date", [pid]), g = await query(pool, "SELECT * FROM grievance_cases WHERE provider_id=? ORDER BY id DESC LIMIT 10", [pid]);
  return { provider, kpis: c.access.providerId ? [] : await cards(c.pid, pid), trainings: (await listTrainings(c, { providerId: pid, pageSize: "200" })).items, obligations: ob.map((o) => ({ id: o["id"], providerId: pid, providerCode: provider.code, activity: { code: o["code"], name: o["name"], scope: o["scope"] }, scopeLabel: o["kc"] ?? o["title"] ?? provider.name, openDate: o["open_date"], dueDate: o["due_date"], closeDate: o["close_date"], status: o["status"] })), staff: await listMembers(c.pid, pid),
    targets: c.access.providerId ? [] : defs.map((d) => ({ indicator: { code: d["code"], no: d["protocol_no"] ?? 0, name: d["name"], level: d["level"], unit: d["unit"] === "count" ? "#" : "%", direction: d["direction"], defaultTarget: Number(d["default_target"] ?? 0) }, target: opt(own.filter((x) => x["c"] === d["code"]).at(-1)?.["v"]), default: Number(d["default_target"] ?? 0) })),
    grievances: g.map((x) => ({ id: x["id"], ref: x["ref"], providerId: pid, providerName: provider.name, category: x["category"], subject: x["subject"], status: x["status"], submittedAt: x["submitted_at"], dueAt: x["due_at"], overdue: !x["first_response_at"] && Date.parse(x["due_at"]) < Date.now(), submitterName: "", submitterEmail: "", description: "", messages: [] })),
    contract: { number: cur?.["contract_number"] ?? "", signedDate: cur?.["signed_date"] ?? "", start: cur?.["start_date"] ?? "", end: cur?.["end_date"] ?? "", target: cur?.["target_trainees"] ?? 0, status: cur?.["status"] ?? "", versions: k.map((x, i) => ({ version: i + 1, target: x["target_trainees"], effectiveFrom: x["effective_from"] ?? "", note: x["notes"] ?? "" })) } };
}
export interface Onboarding { code: string; name: string; legalName?: string | undefined; contactName: string; contactPhone: string; notificationEmail: string; replyToEmail: string; requiresExternalId: boolean; externalIdLabel?: string | undefined; contract: { number: string; signedDate: string; start: string; end: string; target: number; levels: string[]; locationCodes: string[] }; targets: Record<string, number>; admin: { name: string; email: string }; registrationWindow: { from: string; until: string } }
/** The whole onboarding is saved together, so a provider never exists half set up. */
export async function create(c: Ctx, b: Onboarding) {
  const code = b.code.trim().toUpperCase(), phone = parsePhone(b.contactPhone);
  if (await one(pool, "SELECT 1 AS x FROM providers WHERE project_id=? AND code=?", [c.pid, code])) invalid("code", "Another provider uses this code.");
  if (b.contract.end <= b.contract.start) invalid("contract.end", "The end date must be after the start date.");
  if (b.registrationWindow.until < b.registrationWindow.from) invalid("registrationWindow.until", "The last day is before the first day.");
  const id = await transaction(async (tx) => {
    const pid = await insert(tx, "providers", { project_id: c.pid, code, name: b.name, legal_name: b.legalName, status: "onboarding", contact_name: b.contactName, contact_phone_raw: b.contactPhone, contact_phone_e164: phone.ok ? phone.e164 : null, contact_email: b.notificationEmail, notification_email: b.notificationEmail, reply_to_email: b.replyToEmail, requires_external_id: b.requiresExternalId, external_id_label: b.externalIdLabel, registration_open_from: b.registrationWindow.from, registration_open_until: b.registrationWindow.until });
    await insert(tx, "provider_contracts", { project_id: c.pid, provider_id: pid, contract_number: b.contract.number, signed_date: b.contract.signedDate, start_date: b.contract.start, end_date: b.contract.end, target_trainees: b.contract.target, effective_from: b.contract.start, levels_json: JSON.stringify({ levels: b.contract.levels, locationCodes: b.contract.locationCodes }), status: "active", set_by: c.user.id });
    for (const [k, v] of Object.entries(b.targets)) if (await one(tx, "SELECT 1 AS x FROM indicator_definitions WHERE project_id=? AND code=? AND status='active'", [c.pid, k])) await execute(tx, "INSERT INTO indicator_targets (project_id, indicator_code, provider_id, target_value, comparator, effective_from, note, set_by) SELECT project_id, code, ?, ?, comparator, ?, 'Set at onboarding', ? FROM indicator_definitions WHERE project_id=? AND code=? AND status='active'", [pid, v, b.contract.start, c.user.id, c.pid, k]);
    await assignProvider(tx, c.pid, pid);
    await invite(tx, c, { name: b.admin.name, email: b.admin.email, roleCode: "tp_admin", providerId: pid });
    await audit(tx, c, { module: "providers", action: "created", entityType: "provider", entityId: pid, providerId: pid, summary: `Provider ${code} created`, after: b });
    return pid;
  });
  return view(c, id);
}
async function change(c: Ctx, pid: string, action: string, cols: Row, note?: string) {
  const p = await row(c, pid);
  await transaction(async (tx) => { await update(tx, "providers", pid, { ...cols, version: p["version"] + 1 }); await audit(tx, c, { module: "providers", action, entityType: "provider", entityId: pid, providerId: pid, summary: `Provider ${p["code"]}: ${action.replace(/_/g, " ")}`, before: Object.fromEntries(Object.keys(cols).map((k) => [k, p[k]])), after: { ...cols, note } }); if (cols["status"]) { await materialize(tx, c.pid); await queueKpis(tx, c.pid); } });
  return view(c, pid);
}
export async function activate(c: Ctx, pid: string) {
  if (!(await one(pool, "SELECT 1 AS x FROM provider_contracts WHERE provider_id=? AND status='active'", [pid]))) conflict("NO_CONTRACT", "Add an active contract first.");
  return change(c, pid, "activated", { status: "active", onboarding_completed_at: new Date().toISOString().slice(0, 23).replace("T", " ") });
}
/** The provider's own email addresses, which its admin may change, as in V1. */
export function emails(c: Ctx, pid: string, b: { notificationEmail?: string | undefined; replyToEmail?: string | undefined }) {
  sameProvider(c, pid);
  return change(c, pid, "updated", { ...(b.notificationEmail ? { notification_email: b.notificationEmail } : {}), ...(b.replyToEmail ? { reply_to_email: b.replyToEmail } : {}) });
}
export const edit = (c: Ctx, pid: string, b: Row) => change(c, pid, "updated", Object.fromEntries(Object.entries({ name: "name", legalName: "legal_name", contactName: "contact_name", contactPhone: "contact_phone_raw", contactEmail: "contact_email", notificationEmail: "notification_email", replyToEmail: "reply_to_email", status: "status", requiresExternalId: "requires_external_id", externalIdLabel: "external_id_label" }).filter(([k]) => b[k] !== undefined).map(([k, col]) => [col, b[k]])));
export async function setWindow(c: Ctx, pid: string, b: { from?: string | undefined; until?: string | undefined; late?: { until: string; reason: string } | undefined; closed?: boolean | undefined; note?: string | undefined }) {
  if (!(await getSettings(c.pid)).registrationOpen) conflict("REGISTRATION_CLOSED", "Registration is closed for the whole project in Settings. Open it there first.");
  if (b.late && b.late.until < today()) invalid("late.until", "Choose a date from today.");
  if (b.from && b.until && b.until < b.from) invalid("until", "The last day is before the first day.");
  const cols = b.late ? { registration_late_until: b.late.until, registration_closed_at: null, registration_close_note: b.late.reason } : { ...(b.from ? { registration_open_from: b.from } : {}), ...(b.until ? { registration_open_until: b.until } : {}), ...(b.closed === undefined ? {} : { registration_closed_at: b.closed ? new Date().toISOString().slice(0, 23).replace("T", " ") : null, registration_closed_by: b.closed ? c.user.id : null, registration_close_note: b.note ?? null }) };
  return change(c, pid, b.late ? "late_registration" : "registration_window", cols, b.late?.reason);
}
export async function registration(c: Ctx, pid: string) { const p = await view(c, pid), s = await getSettings(c.pid); return { projectOpen: s.registrationOpen, window: p.registrationWindow, registered: p.registered, max: p.maxRegistration, target: p.contractTarget }; }
export async function amend(c: Ctx, pid: string, b: { target: number; effectiveFrom: string; note: string }) {
  const p = await row(c, pid), old = await one(pool, "SELECT * FROM provider_contracts WHERE provider_id=? AND status='active' ORDER BY id DESC LIMIT 1", [pid]), r = await providerRules(pool, pid);
  if (maxRegistration(b.target, r["pct"]) < r["registered"]) invalid("target", `${r["registered"]} trainees are already registered.`);
  await transaction(async (tx) => {
    if (old) await update(tx, "provider_contracts", old["id"], { status: "amended" });
    await insert(tx, "provider_contracts", { project_id: c.pid, provider_id: pid, contract_number: old?.["contract_number"], signed_date: old?.["signed_date"], start_date: old?.["start_date"], end_date: old?.["end_date"], levels_json: old?.["levels_json"], target_trainees: b.target, effective_from: b.effectiveFrom, notes: b.note, status: "active", supersedes_id: old?.["id"], set_by: c.user.id });
    await queueKpis(tx, c.pid);
    await audit(tx, c, { module: "providers", action: "contract_amended", entityType: "provider", entityId: pid, providerId: pid, summary: `Contract target of ${p["code"]}: ${b.target}`, before: { target: old?.["target_trainees"] }, after: b });
  });
  return { ok: true };
}
/** Signed date, number and period can be filled in later; V1 did not store them. */
export async function contractDetails(c: Ctx, pid: string, b: { number?: string | undefined; signedDate?: string | undefined; start?: string | undefined; end?: string | undefined }) {
  await row(c, pid);
  const k = (await one(pool, "SELECT * FROM provider_contracts WHERE provider_id=? AND status='active' ORDER BY id DESC LIMIT 1", [pid])) ?? notFound("Contract");
  await transaction(async (tx) => { await update(tx, "provider_contracts", k["id"], { contract_number: b.number, signed_date: b.signedDate, start_date: b.start, end_date: b.end }); await materialize(tx, c.pid); await audit(tx, c, { module: "providers", action: "contract_details", entityType: "provider", entityId: pid, providerId: pid, summary: "Contract details saved", before: k, after: b }); });
  return { ok: true };
}
export async function addStaff(c: Ctx, pid: string, b: { name: string; email: string; roleCode: string; scopes: string[] }) {
  await row(c, pid);
  const mid = await transaction((tx) => invite(tx, c, { ...b, providerId: pid }));
  return (await listMembers(c.pid, pid)).find((m) => m.id === mid);
}
export const staff = async (c: Ctx, pid: string) => { await row(c, pid); return listMembers(c.pid, pid); };
export async function byLocation(c: Ctx, pid: string) { await row(c, pid); return query(pool, "SELECT COALESCE(l.name,'Unassigned') AS location, SUM(s.sex='male') AS male, SUM(s.sex='female') AS female, SUM(s.roster_status='active') AS active, SUM(s.roster_status='reserve') AS reserve, COUNT(*) AS total FROM trainee_status s LEFT JOIN locations l ON l.id=s.location_id WHERE s.provider_id=? AND s.roster_status IN ('active','reserve') GROUP BY l.name ORDER BY l.name", [pid]); }
void addDays; void enqueue;
