import { consola } from "consola";
import { getAllActiveMailUserIds } from "../db/mail";

const SCAN_INTERVAL = 30 * 60 * 1000; // every 30 minutes (proxy EXISTS handles real-time)

export default defineNitroPlugin((nitro) => {
  if (import.meta.dev) return;

  consola.info("[mail-scan-cron] Starting – scanning due accounts every 30 min");

  const interval = setInterval(runScan, SCAN_INTERVAL);
  nitro.hooks.hook("close", () => clearInterval(interval));
});

async function runScan() {
  let userIds: string[];
  try {
    userIds = await getAllActiveMailUserIds();
  } catch {
    return;
  }

  if (userIds.length === 0) return;

  const adminSecret = process.env.NUXT_ADMIN_SECRET || process.env.ADMIN_SECRET;
  if (!adminSecret) return;

  await Promise.allSettled(
    userIds.map((userId) =>
      $fetch("/api/mail/scan-internal", {
        method: "POST",
        headers: { "x-admin-secret": adminSecret },
        body: { userId },
      }).catch(() => {})
    )
  );
}
