import { execute, query, type Db, type Row } from "../../core/db/db.js";
import { diffDays, today } from "../../shared/dates.js";
import { pickSchedule, statusOn, windows, type Schedule } from "./schedule.rules.js";

export interface Planned { definitionId: string; providerId: string; trainingId: string | null; siteId: string | null; classId: string | null; scopeKey: string; seq: number; open: string; due: string; close: string; scheduleId: string; version: number }
/** Works out every obligation from the schedules and the real dates of contracts, trainings, sites and classes. */
export async function plan(db: Db, pid: string, providerId?: string): Promise<Planned[]> {
  const defs = await query(db, "SELECT * FROM activity_definitions WHERE project_id=? AND is_active=1", [pid]), assigned = await query(db, "SELECT definition_id, provider_id FROM activity_assignments");
  const sch = (await query(db, "SELECT s.* FROM activity_schedules s JOIN activity_definitions d ON d.id=s.definition_id WHERE d.project_id=? AND s.is_active=1", [pid])).map((s) => ({ id: String(s["id"]), def: String(s["definition_id"]), anchor: s["anchor"], openOffset: s["open_offset_days"], dueOffset: s["due_offset_days"], graceDays: s["grace_days"], repeatEvery: s["repeat_every_days"], repeatCount: s["repeat_count"], level: s["applies_level"], durationId: s["applies_duration_id"], providerId: s["applies_provider_id"], extends: Boolean(s["breakdown_extends"]), version: s["schedule_version"] as number }) as Schedule & { def: string; extends: boolean; version: number });
  const providers = await query(db, `SELECT p.id, (SELECT MIN(COALESCE(k.signed_date,k.effective_from)) FROM provider_contracts k WHERE k.provider_id=p.id AND k.status IN ('active','amended')) AS signed, (SELECT MIN(COALESCE(c.actual_start,c.planned_start)) FROM training_classes c WHERE c.provider_id=p.id AND c.is_cancelled=0) AS first FROM providers p WHERE p.project_id=? AND p.status IN ('active','suspended') ${providerId ? "AND p.id=?" : ""}`, providerId ? [pid, providerId] : [pid]);
  const trainings = await query(db, "SELECT id, provider_id, level, duration_id, planned_start FROM trainings WHERE project_id=?", [pid]), sites = await query(db, "SELECT s.id, s.provider_id, s.training_id, MIN(COALESCE(c.actual_start,c.planned_start)) AS first, MAX(c.effective_end) AS last FROM training_sites s JOIN training_classes c ON c.site_id=s.id AND c.is_cancelled=0 WHERE s.project_id=? GROUP BY s.id, s.provider_id, s.training_id", [pid]);
  const classes = await query(db, "SELECT c.id, c.provider_id, c.training_id, c.site_id, COALESCE(c.actual_start,c.planned_start) AS start, c.effective_end AS end FROM training_classes c WHERE c.project_id=? AND c.is_cancelled=0", [pid]), breaks = await query(db, "SELECT * FROM training_breakdowns WHERE project_id=? AND status='approved'", [pid]);
  const lost = (k: Row) => breaks.filter((b) => b["training_id"] === k["training_id"] && (b["class_id"] ? b["class_id"] === k["id"] : !b["site_id"] || b["site_id"] === k["site_id"]) && b["start_date"] <= k["end"] && b["end_date"] >= k["start"]).reduce((a, b) => a + diffDays(b["start_date"], b["end_date"]) + 1, 0);
  // A training is submitted once, for all its classes: it starts with the first class and ends with the last.
  const of = (t: Row) => classes.filter((k) => k["training_id"] === t["id"]), first = (t: Row) => of(t).map((k) => k["start"] as string).sort()[0] ?? null, last = (t: Row) => of(t).map((k) => k["end"] as string).sort().at(-1) ?? null;
  const out: Planned[] = [];
  for (const d of defs) {
    const only = assigned.filter((a) => a["definition_id"] === d["id"]).map((a) => a["provider_id"]), mine = sch.filter((s) => s.def === String(d["id"]));
    for (const p of providers) {
      if (only.length && !only.includes(p["id"])) continue;
      const add = (scopeKey: string, ids: { trainingId?: string; siteId?: string; classId?: string }, t: Row | undefined, anchors: Record<string, string | null>, extra = 0) => {
        const s = pickSchedule(mine, { providerId: String(p["id"]), durationId: t?.["duration_id"] ?? null, level: t?.["level"] ?? null }), anchor = s ? anchors[s.anchor] : null;
        if (s && anchor) for (const w of windows(s, anchor, s.extends ? extra : 0)) out.push({ definitionId: String(d["id"]), providerId: String(p["id"]), trainingId: ids.trainingId ?? null, siteId: ids.siteId ?? null, classId: ids.classId ?? null, scopeKey, seq: w.seq, open: w.open, due: w.due, close: w.close, scheduleId: s.id, version: s.version });
      };
      const base = { contract_signed_date: p["signed"], provider_first_class_start: p["first"] };
      if (d["scope"] === "provider") add("provider", {}, undefined, base);
      for (const t of trainings.filter((x) => x["provider_id"] === p["id"])) {
        if (d["scope"] === "training") add(`training:${t["id"]}`, { trainingId: t["id"] }, t, { ...base, training_planned_start: t["planned_start"], class_start: first(t), class_end: last(t) }, Math.max(0, ...of(t).map(lost)));
        for (const s of sites.filter((x) => x["training_id"] === t["id"])) if (d["scope"] === "site") add(`site:${s["id"]}`, { trainingId: t["id"], siteId: s["id"] }, t, { ...base, training_planned_start: t["planned_start"], site_first_class_start: s["first"], class_start: s["first"], class_end: s["last"] });
        if (d["scope"] === "class") for (const k of classes.filter((x) => x["training_id"] === t["id"])) { const site = sites.find((s) => s["id"] === k["site_id"]); add(`class:${k["id"]}`, { trainingId: t["id"], siteId: k["site_id"], classId: k["id"] }, t, { ...base, training_planned_start: t["planned_start"], site_first_class_start: site?.["first"], class_start: k["start"], class_end: k["end"] }, lost(k)); }
      }
    }
  }
  return out;
}
/** Creates missing obligations and moves the dates of undecided ones. Approved, waived and submitted ones are never touched. */
export async function materialize(db: Db, pid: string, now = today()): Promise<{ created: number; moved: number }> {
  const old = new Map((await query(db, "SELECT * FROM activity_obligations WHERE project_id=?", [pid])).map((o) => [`${o["provider_id"]}:${o["definition_id"]}:${o["scope_key"]}:${o["sequence_no"]}`, o]));
  let created = 0, moved = 0;
  for (const p of await plan(db, pid)) {
    const o = old.get(`${p.providerId}:${p.definitionId}:${p.scopeKey}:${p.seq}`);
    if (!o) { await execute(db, "INSERT INTO activity_obligations (project_id, provider_id, definition_id, training_id, site_id, class_id, scope_key, sequence_no, open_date, due_date, close_date, status, schedule_id, schedule_version) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", [pid, p.providerId, p.definitionId, p.trainingId, p.siteId, p.classId, p.scopeKey, p.seq, p.open, p.due, p.close, statusOn("open", p, now), p.scheduleId, p.version]); created++; }
    else if (["upcoming", "open", "overdue"].includes(o["status"])) {
      const extended = await query(db, "SELECT 1 AS x FROM activity_obligation_notes WHERE obligation_id=? AND kind='extended'", [o["id"]]), due = extended.length && o["due_date"] > p.due ? o["due_date"] : p.due, close = extended.length && o["close_date"] > p.close ? o["close_date"] : p.close, status = statusOn(o["status"], { open: p.open, due }, now);
      if (o["open_date"] !== p.open || o["due_date"] !== due || o["close_date"] !== close || o["status"] !== status) { await execute(db, "UPDATE activity_obligations SET open_date=?, due_date=?, close_date=?, status=?, schedule_id=?, schedule_version=? WHERE id=?", [p.open, due, close, status, p.scheduleId, p.version, o["id"]]); moved++; }
    }
  }
  return { created, moved };
}
