import { env } from "../../config/env.js";
import { one, pool, query } from "../../core/db/db.js";
import { defineJob } from "../../core/jobs/jobs.js";
import { queueMail } from "../../core/mail/mail.js";
import { today } from "../../shared/dates.js";

/** One email per person with yesterday's unread notices, for the kinds they set to "daily digest". */
export async function digest(pid: string, day = today()): Promise<number> {
  const rows = await query(pool, "SELECT u.id, u.name, u.email, n.title, n.link FROM notifications n JOIN users u ON u.id=n.user_id AND u.status='active' JOIN notification_preferences f ON f.user_id=u.id AND f.type=n.type AND f.email='daily_digest' WHERE n.project_id=? AND n.read_at IS NULL AND n.created_at>=UTC_TIMESTAMP(3)-INTERVAL 1 DAY ORDER BY u.id, n.id", [pid]), people = new Map<string, typeof rows>();
  for (const r of rows) people.set(r["id"], [...(people.get(r["id"]) ?? []), r]);
  for (const [id, list] of people) await queueMail(pool, { projectId: pid, to: list[0]!["email"], subject: `PBPS MIS: ${list.length} notices`, text: [`Hello ${list[0]!["name"]},`, ...list.slice(0, 40).flatMap((n) => [n["title"] as string, ...(n["link"] ? [`${env.APP_URL}${n["link"]}`] : [])]), ...(list.length > 40 ? [`And ${list.length - 40} more.`] : [])].join("\n"), template: "digest.daily", dedupe: `digest:${id}:${day}` });
  return people.size;
}
/** Monday summary for M&E: indicators below target, overdue activities and unanswered grievances. */
export async function weekly(pid: string, day = today()): Promise<number> {
  const n = async (sql: string) => Number((await one(pool, sql, [pid]))!["n"]);
  const low = await query(pool, "SELECT p.code, d.name, k.value, k.target_value AS t FROM kpi_snapshots k JOIN providers p ON p.id=k.provider_key JOIN indicator_definitions d ON d.project_id=k.project_id AND d.code=k.indicator_code AND d.status='active' WHERE k.project_id=? AND k.layer='monitoring' AND k.status='not_met' AND k.as_of_date=(SELECT MAX(as_of_date) FROM kpi_snapshots x WHERE x.project_id=k.project_id) ORDER BY p.code, d.display_order", [pid]);
  const text = [`Indicators below target: ${low.length}`, ...low.slice(0, 30).map((l) => `${l["code"]}: ${l["name"]} ${l["value"]} (target ${l["t"]})`), `Overdue activities: ${await n("SELECT COUNT(*) AS n FROM activity_obligations WHERE project_id=? AND status='overdue'")}`, `Activities waiting for review: ${await n("SELECT COUNT(*) AS n FROM activity_obligations WHERE project_id=? AND status='submitted'")}`, `Grievances past their deadline: ${await n("SELECT COUNT(*) AS n FROM grievance_cases WHERE project_id=? AND first_response_at IS NULL AND due_at<UTC_TIMESTAMP(3)")}`, `${env.APP_URL}/p/${pid}/dashboard`].join("\n");
  const to = await query(pool, "SELECT DISTINCT u.id, u.email, u.name 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 WHERE m.project_id=? AND m.status='active' AND r.code IN ('me_lead','me_officer')", [pid]);
  for (const u of to) await queueMail(pool, { projectId: pid, to: u["email"], subject: "PBPS MIS: weekly summary", text: `Hello ${u["name"]},\n${text}`, template: "digest.weekly", dedupe: `weekly:${u["id"]}:${day}` });
  return to.length;
}
defineJob("digest.daily", async (job) => ({ message: `${await digest(job.projectId!)} digests.` }));
defineJob("digest.weekly", async (job) => ({ message: `${await weekly(job.projectId!)} summaries.` }));
