import { prisma } from "../prisma.js";
import { env } from "../env.js";
import { evaluateProjectAlerts } from "./alertEngine.js";
import { deliverAlertEmails, sendAdminDailyDigest } from "./alertDelivery.js";
import { ensureDefaultAlertRules } from "./alertRules.js";
import { ALERTS_ENABLED_KEY, ALERTS_INTERVAL_MINUTES_KEY, getBoolSetting, getNumberSetting } from "./appSettings.js";

let running = false;
let lastCompletedAt: Date | null = null;

async function runAlertCycle() {
  if (running) return;
  running = true;
  try {
    const projects = await prisma.project.findMany({
      select: { id: true, projectCode: true },
      orderBy: { id: "asc" },
      take: 2000,
    });
    for (const project of projects) {
      try {
        await ensureDefaultAlertRules(project.id);
        const out = await evaluateProjectAlerts(project.id, new Date());
        await deliverAlertEmails({
          projectId: project.id,
          alerts: out.candidates.map((x) => ({
            eventId: x.event.id as bigint,
            smtpEnabled: x.smtpEnabled,
            cooldownMinutes: x.cooldownMinutes,
          })),
        });
        await sendAdminDailyDigest(project.id, out.adminUserIds, new Date());
      } catch (error) {
        console.error(`[alerts:scheduler] project ${project.projectCode} failed:`, error instanceof Error ? error.message : String(error));
      }
    }
  } finally {
    running = false;
  }
}

export function startAlertScheduler() {
  if (!env.ALERT_SCHEDULER_ENABLED) {
    console.log("[alerts:scheduler] disabled by env.");
    return;
  }
  const heartbeatMinutes = 5;
  const intervalMs = heartbeatMinutes * 60 * 1000;
  console.log(`[alerts:scheduler] enabled. heartbeat=${heartbeatMinutes}m, interval managed via Settings > Alerts`);

  // Kick once on boot so users don't wait for the first interval.
  void (async () => {
    const enabled = await getBoolSetting(prisma, ALERTS_ENABLED_KEY, true);
    if (enabled) {
      await runAlertCycle();
    } else {
      console.log("[alerts:scheduler] skipped initial run (disabled in settings).");
    }
  })();

  setInterval(() => {
    void (async () => {
      const enabled = await getBoolSetting(prisma, ALERTS_ENABLED_KEY, true);
      if (!enabled) return;
      const intervalMinutes = Math.max(5, Math.min(1440, await getNumberSetting(prisma, ALERTS_INTERVAL_MINUTES_KEY, env.ALERT_EVALUATION_INTERVAL_MINUTES)));
      if (lastCompletedAt) {
        const elapsedMs = Date.now() - lastCompletedAt.getTime();
        if (elapsedMs < intervalMinutes * 60 * 1000) return;
      }
      await runAlertCycle();
      lastCompletedAt = new Date();
    })();
  }, intervalMs);
}
