import { env } from "../../config/env.js";
import { audit } from "../../core/audit/audit.js";
import { encrypt } from "../../core/crypto.js";
import { execute, json, one, pool, query, transaction, type Db, type Row } from "../../core/db/db.js";
import { conflict, notFound, type Ctx } from "../../core/http/route.js";
import { defineJob } from "../../core/jobs/jobs.js";
import { queueMail } from "../../core/mail/mail.js";
import { addDays, today } from "../../shared/dates.js";

export interface Notice { providerId?: string | null; roles: string[]; type: string; severity: "info" | "warning" | "critical"; title: string; body?: string; link?: string; dedupe: string; email?: boolean }
/** One notice per person and event. The dedupe key makes a repeated run harmless. Email is sent only for a notice that is new. */
export async function notifyRoles(db: Db, pid: string, n: Notice): Promise<number> {
  const users = await query(db, `SELECT DISTINCT u.id, u.email, u.name, f.in_app, f.email AS pref FROM memberships m JOIN users u ON u.id=m.user_id AND u.status='active' JOIN roles r ON r.id=m.role_id LEFT JOIN notification_preferences f ON f.user_id=u.id AND f.type=? WHERE m.project_id=? AND m.status='active' AND r.code IN (?) AND (m.provider_id IS NULL OR m.provider_id=?)`, [n.type, pid, n.roles, n.providerId ?? "0"]);
  let created = 0;
  for (const u of users) {
    if (u["in_app"] === 0 && n.severity !== "critical") continue;
    const r = await execute(db, "INSERT IGNORE INTO notifications (project_id, user_id, type, severity, title, body, link, dedupe_key) VALUES (?,?,?,?,?,?,?,?)", [pid, u["id"], n.type, n.severity, n.title.slice(0, 190), n.body ?? null, n.link ?? null, `${n.dedupe}:${u["id"]}`]);
    if (!r.affectedRows) continue;
    created++;
    if (n.email && (u["pref"] ?? "immediate") === "immediate") await queueMail(db, { projectId: pid, to: u["email"], subject: n.title, text: `Hello ${u["name"]},\n${n.title}${n.body ? `\n${n.body}` : ""}${n.link ? `\n${env.APP_URL}${n.link}` : ""}`, template: n.type, dedupe: `${n.dedupe}:${u["id"]}` });
  }
  return created;
}
const view = (n: Row) => ({ id: n["id"], type: n["type"], severity: n["severity"], title: n["title"], body: n["body"] ?? undefined, link: n["link"] ?? undefined, createdAt: n["created_at"], readAt: n["read_at"] ?? undefined });
export const list = async (c: Ctx) => (await query(pool, "SELECT * FROM notifications WHERE project_id=? AND user_id=? ORDER BY id DESC LIMIT 200", [c.pid, c.user.id])).map(view);
export const unread = async (c: Ctx) => ({ count: (await one(pool, "SELECT COUNT(*) AS n FROM notifications WHERE project_id=? AND user_id=? AND read_at IS NULL", [c.pid, c.user.id]))!["n"] });
export const mark = async (c: Ctx, nid: string, read: boolean) => { await execute(pool, "UPDATE notifications SET read_at=IF(?,UTC_TIMESTAMP(3),NULL) WHERE id=? AND user_id=?", [read, nid, c.user.id]); };
export const markAll = async (c: Ctx) => { await execute(pool, "UPDATE notifications SET read_at=UTC_TIMESTAMP(3) WHERE project_id=? AND user_id=? AND read_at IS NULL", [c.pid, c.user.id]); };
const TYPES: [string, string, boolean][] = [["grievance.new_case", "New grievance", true], ["grievance.due", "Grievance due or overdue", true], ["activity.obligation_due", "Activity due or overdue", false], ["attendance.missing", "Missing attendance", false], ["outcome.report_due", "Outcome report due", false], ["roster.freeze_upcoming", "Registration of a class closes soon", false], ["dropout.risk", "Trainees at risk of dropout", false], ["registration.window_closing", "Registration closes soon", false]];
export async function prefs(c: Ctx) { const p = await query(pool, "SELECT * FROM notification_preferences WHERE user_id=?", [c.user.id]); return TYPES.map(([type, label, mandatory]) => { const x = p.find((y) => y["type"] === type); return { type, label, inApp: mandatory || !x || Boolean(x["in_app"]), email: x?.["email"] ?? "immediate", mandatory }; }); }
export async function savePrefs(c: Ctx, b: { type: string; inApp: boolean; email: string }[]) { for (const p of b) { const t = TYPES.find(([k]) => k === p.type); if (t) await execute(pool, "INSERT INTO notification_preferences (user_id, type, in_app, email) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE in_app=VALUES(in_app), email=VALUES(email)", [c.user.id, p.type, t[2] || p.inApp, p.email]); } }
export async function mail() { const m = await one(pool, "SELECT * FROM mail_settings WHERE id=1"); return { host: m?.["smtp_host"] ?? "", port: m?.["smtp_port"] ?? 587, security: m?.["smtp_secure"] ?? "starttls", user: m?.["smtp_user"] ?? "", fromName: m?.["from_name"] ?? "", fromEmail: m?.["from_email"] ?? "", enabled: Boolean(m?.["is_enabled"]), passwordSet: Boolean(m?.["smtp_password_enc"]), delivery: env.MAIL_DELIVERY }; }
export async function saveMail(c: Ctx, b: Row) {
  const o = await mail(), n = { ...o, ...b };
  await transaction(async (tx) => {
    // A new server must not receive the old server's password.
    const moved = n["host"] !== o.host || n["user"] !== o.user, pass = b["password"] ? encrypt(b["password"]) : null;
    await execute(tx, "INSERT INTO mail_settings (id, from_name, from_email, smtp_host, smtp_port, smtp_secure, smtp_user, smtp_password_enc, is_enabled, updated_by) VALUES (1,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE from_name=VALUES(from_name), from_email=VALUES(from_email), smtp_host=VALUES(smtp_host), smtp_port=VALUES(smtp_port), smtp_secure=VALUES(smtp_secure), smtp_user=VALUES(smtp_user), smtp_password_enc=IF(VALUES(smtp_password_enc) IS NULL, IF(?,NULL,smtp_password_enc), VALUES(smtp_password_enc)), is_enabled=VALUES(is_enabled), updated_by=VALUES(updated_by)", [n["fromName"], n["fromEmail"], n["host"], n["port"], n["security"], n["user"] || null, pass, n["enabled"], c.user.id, moved]);
    await audit(tx, c, { module: "notifications", action: "mail_settings", summary: "Mail settings changed", before: o, after: { ...b, password: undefined } });
  });
  return mail();
}
export async function test(c: Ctx, to: string) { await queueMail(pool, { to, subject: "PBPS MIS test email", text: "This is a test. Email works.", template: "system.test" }); await audit(pool, c, { module: "notifications", action: "mail_test", summary: `Test email queued to ${to}` }); return { ok: true }; }
const out = (m: Row) => ({ id: m["id"], to: m["to_email"], subject: m["subject"], template: m["template_key"], status: m["status"], attempts: m["attempts"], createdAt: m["created_at"], sentAt: m["sent_at"] ?? undefined, error: m["last_error"] ?? undefined });
/** Bodies are never listed: they can hold one-time links and codes. */
export const outbox = async (c: Ctx) => (await query(pool, `SELECT * FROM email_outbox ${c.query["status"] ? "WHERE status=?" : ""} ORDER BY id DESC LIMIT 200`, c.query["status"] ? [c.query["status"]] : [])).map(out);
export async function retry(c: Ctx, mid: string) { const r = await execute(pool, "UPDATE email_outbox SET status='queued', attempts=0, next_attempt_at=UTC_TIMESTAMP(3) WHERE id=? AND status IN ('failed','dead')", [mid]); if (!r.affectedRows) conflict("NOT_FAILED", "Only a failed email can be sent again."); await audit(pool, c, { module: "notifications", action: "mail_retry", summary: `Email ${mid} queued again` }); return out((await one(pool, "SELECT * FROM email_outbox WHERE id=?", [mid])) ?? notFound("Email")); }
const RULES: Record<string, string> = { "obligation.due": "Activity due", "obligation.overdue": "Activity overdue", "attendance.missing": "Missing attendance", "dropout.risk_digest": "Trainees at risk of dropout", "grievance.sla": "Grievance deadline", "grievance.escalate": "Grievance escalation", "outcome.report_due": "Outcome report due", "roster.freeze_upcoming": "Registration of a class closes soon", "registration.window_closing": "Registration closes soon" };
export const rules = async (c: Ctx) => (await query(pool, "SELECT * FROM reminder_rules WHERE project_id=? ORDER BY id", [c.pid])).map((r) => ({ key: r["rule_key"], label: RULES[r["rule_key"]] ?? r["rule_key"], offsets: json<number[]>(r["offsets_json"], []), repeatAfter: r["repeat_after_days"] ?? undefined, severity: r["severity"], email: Boolean(r["email_enabled"]), enabled: Boolean(r["is_enabled"]) }));
export async function saveRules(c: Ctx, b: { key: string; offsets: number[]; repeatAfter?: number | undefined; severity: string; email: boolean; enabled: boolean }[]) { await transaction(async (tx) => { for (const r of b) await execute(tx, "UPDATE reminder_rules SET offsets_json=?, repeat_after_days=?, severity=?, email_enabled=?, is_enabled=? WHERE project_id=? AND rule_key=?", [JSON.stringify(r.offsets), r.repeatAfter ?? null, r.severity, r.email, r.enabled, c.pid, r.key]); await audit(tx, c, { module: "notifications", action: "reminder_rules", summary: "Reminder rules changed", after: b }); }); return rules(c); }
const TP = ["tp_admin", "tp_site_lead"], ME = ["me_lead", "me_officer"];
/** Finds what is due today and tells the people concerned. Offsets are days before (-) or after (+) the date. */
export async function reminders(pid: string, now = today()): Promise<number> {
  if (json<boolean>((await one(pool, "SELECT value_json AS v FROM app_settings WHERE setting_key='reminders.enabled'"))?.["v"], true) === false) return 0;
  const all = await query(pool, "SELECT * FROM reminder_rules WHERE project_id=? AND is_enabled=1", [pid]);
  let n = 0;
  const dates = (r: Row) => { const o = json<number[]>(r["offsets_json"], []), rep = r["repeat_after_days"], last = Math.max(...o, 0); return rep ? [...o, ...Array.from({ length: 12 }, (_, i) => last + rep * (i + 1))] : o; };
  const base = (r: Row) => ({ severity: r["severity"] as Notice["severity"], email: Boolean(r["email_enabled"]) });
  for (const r of all) for (const off of dates(r)) {
    const day = addDays(now, -off), say = async (x: Omit<Notice, "severity" | "email"> & { email?: boolean }) => { n += await notifyRoles(pool, pid, { ...base(r), ...x }); }, when = off < 0 ? `due in ${-off} days` : off === 0 ? "due today" : `${off} days overdue`;
    if (r["rule_key"].startsWith("obligation.")) for (const o of await query(pool, "SELECT o.id, o.provider_id, d.name FROM activity_obligations o JOIN activity_definitions d ON d.id=o.definition_id WHERE o.project_id=? AND o.due_date=? AND o.status IN ('open','returned','overdue','upcoming')", [pid, day])) await say({ providerId: o["provider_id"], roles: TP, type: "activity.obligation_due", title: `${o["name"]}: ${when}`, link: `/p/${pid}/obligations/${o["id"]}`, dedupe: `ob:${o["id"]}:${off}` });
    if (r["rule_key"] === "grievance.sla") for (const g of await query(pool, "SELECT id, ref, provider_id FROM grievance_cases WHERE project_id=? AND first_response_at IS NULL AND status NOT IN ('resolved','closed') AND DATE(due_at)=?", [pid, day])) await say({ providerId: g["provider_id"], roles: TP, type: "grievance.due", title: `${g["ref"]}: reply ${when}`, link: `/p/${pid}/grievances/${g["id"]}`, dedupe: `grv:${g["id"]}:${off}` });
    if (r["rule_key"] === "grievance.escalate") for (const g of await query(pool, "SELECT id, ref, provider_id FROM grievance_cases WHERE project_id=? AND first_response_at IS NULL AND status NOT IN ('resolved','closed','escalated') AND DATE(due_at)=?", [pid, day])) { await execute(pool, "UPDATE grievance_cases SET status='escalated', escalated_at=UTC_TIMESTAMP(3) WHERE id=?", [g["id"]]); await say({ roles: ME, type: "grievance.due", title: `${g["ref"]} was not answered and is escalated`, link: `/p/${pid}/grievances/${g["id"]}`, dedupe: `esc:${g["id"]}` }); }
    if (r["rule_key"] === "attendance.missing") for (const k of await query(pool, "SELECT c.id, c.code, c.provider_id, k.sessions_missing AS m, c.effective_end>=CURRENT_DATE AS live FROM training_classes c JOIN class_counters k ON k.class_id=c.id WHERE c.project_id=? AND k.sessions_missing>=? AND c.is_cancelled=0", [pid, Math.max(1, off)])) await say({ providerId: k["provider_id"], roles: [...TP, "tp_attendance_clerk"], type: "attendance.missing", title: `${k["code"]}: ${k["m"]} days of attendance are missing`, link: `/p/${pid}/classes/${k["id"]}/attendance`, dedupe: `att:${k["id"]}:${Math.floor(Date.parse(now) / 604_800_000)}`, ...(k["live"] ? {} : { email: false }) });
    if (r["rule_key"] === "outcome.report_due") for (const k of await query(pool, "SELECT c.id, c.code, c.provider_id FROM training_classes c WHERE c.project_id=? AND c.is_cancelled=0 AND c.effective_end=? AND NOT EXISTS (SELECT 1 FROM outcome_reports o WHERE o.class_id=c.id AND o.report_type='dropout' AND o.status='accepted')", [pid, day])) await say({ providerId: k["provider_id"], roles: [...TP, "tp_outcomes_officer"], type: "outcome.report_due", title: `${k["code"]} ended ${off} days ago and has no dropout report`, link: `/p/${pid}/classes/${k["id"]}/outcomes/dropout`, dedupe: `out:${k["id"]}:${off}` });
    if (r["rule_key"] === "roster.freeze_upcoming") for (const k of await query(pool, "SELECT c.id, c.code, c.provider_id FROM training_classes c JOIN projects p ON p.id=c.project_id WHERE c.project_id=? AND c.roster_frozen_at IS NULL AND COALESCE(c.actual_start,c.planned_start)+INTERVAL p.roster_freeze_offset_days DAY=?", [pid, day])) await say({ providerId: k["provider_id"], roles: TP, type: "roster.freeze_upcoming", title: `Registration of ${k["code"]} closes in ${-off} days`, link: `/p/${pid}/classes/${k["id"]}`, dedupe: `frz:${k["id"]}:${off}` });
    if (r["rule_key"] === "registration.window_closing") for (const p of await query(pool, "SELECT id, name FROM providers WHERE project_id=? AND registration_open_until=?", [pid, day])) await say({ providerId: p["id"], roles: ["tp_admin"], type: "registration.window_closing", title: `Registration closes in ${-off} days`, link: `/p/${pid}/trainees`, dedupe: `reg:${p["id"]}:${day}` });
    if (r["rule_key"] === "dropout.risk_digest" && new Date(`${now}T00:00:00Z`).getUTCDay() === 1) for (const p of await query(pool, "SELECT provider_id AS id, SUM(system_dropout_risk) AS n FROM trainee_status WHERE project_id=? AND roster_status IN ('active','reserve') GROUP BY provider_id HAVING n>0", [pid])) await say({ providerId: String(p["id"]), roles: TP, type: "dropout.risk", title: `${p["n"]} trainees are at risk of dropout`, link: `/p/${pid}/attendance/dropouts`, dedupe: `risk:${p["id"]}:${now}` });
  }
  return n;
}
defineJob("reminders.run", async (job) => ({ message: `${await reminders(job.projectId!)} notices created.` }));
