import { randomUUID } from "node:crypto";
import "./app/moduleRegistry.js";
import { pool } from "./core/db/db.js";
import { enqueue, holdLease, projectIds, runNextJob } from "./core/jobs/jobs.js";
import { deliverOutbox } from "./core/mail/mail.js";
import { scheduleBackup } from "./modules/backups/index.js";
import { today } from "./shared/dates.js";

const me = randomUUID(), sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
let running = true, nightly = "", daily = "", lastMail = 0, lastBackup = 0, lastRemind = 0;
for (const s of ["SIGINT", "SIGTERM"] as const) process.once(s, () => { running = false; });
/** Only the worker that holds the lease schedules work; every worker may run it. */
async function schedule(): Promise<void> {
  if (!(await holdLease("scheduler", me, 120))) return;
  const day = today(), now = Date.now();
  if (now - lastMail > 30_000) { lastMail = now; await deliverOutbox(); }
  if (now - lastBackup > 300_000) { lastBackup = now; await scheduleBackup(now); }
  if (now - lastRemind > 900_000) { lastRemind = now; for (const p of await projectIds()) await enqueue(pool, "reminders.run", {}, { projectId: p, dedupe: `remind:${p}` }); }
  if (daily !== day && new Date(now + 3 * 3_600_000).getUTCHours() >= 7) { daily = day; const monday = new Date(`${day}T00:00:00Z`).getUTCDay() === 1; for (const p of await projectIds()) { await enqueue(pool, "digest.daily", {}, { projectId: p, dedupe: `digest:${p}:${day}` }); if (monday) await enqueue(pool, "digest.weekly", {}, { projectId: p, dedupe: `weekly:${p}:${day}` }); } }
  if (nightly !== day) { nightly = day; for (const p of await projectIds()) { await enqueue(pool, "attendance.recomputeAll", { onlyRunning: true }, { projectId: p, dedupe: `recompute:${p}` }); await enqueue(pool, "activities.materialize", {}, { projectId: p, dedupe: `oblig:${p}` }); await enqueue(pool, "datahealth.run", {}, { projectId: p, dedupe: `health:${p}` }); await enqueue(pool, "roster.autoFreeze", {}, { projectId: p, dedupe: `freeze:${p}` }); await enqueue(pool, "duplicates.scan", {}, { projectId: p, dedupe: `dup:${p}` }); } }
}
while (running) {
  try { await schedule(); if (!(await runNextJob())) await sleep(1000); } catch (error) { console.error("worker", error); await sleep(5000); }
}
await pool.end();
