import { consola } from "consola";

const SYNC_INTERVAL = 60 * 60 * 1000; // 1 hour

export default defineNitroPlugin((nitro) => {
  if (import.meta.dev) {
    consola.info("[blocklist-cron] Skipping cron in dev mode");
    return;
  }

  consola.info("[blocklist-cron] Starting hourly HaGeZi sync");

  // Run initial sync after 30 seconds (let server boot)
  const initialTimer = setTimeout(async () => {
    await runSync();
  }, 30_000);

  // Then run every hour
  const interval = setInterval(async () => {
    await runSync();
  }, SYNC_INTERVAL);

  // Cleanup on close
  nitro.hooks.hook("close", () => {
    clearTimeout(initialTimer);
    clearInterval(interval);
  });
});

async function runSync() {
  try {
    consola.info("[blocklist-cron] Syncing HaGeZi gambling domains...");
    const result = await $fetch("/api/blocklist/sync", { method: "POST" });
    consola.success(
      `[blocklist-cron] Synced ${(result as any).total_fetched} domains`,
    );
  } catch (err: any) {
    consola.error("[blocklist-cron] Sync failed:", err.message ?? err);
  }
}
