/**
 * Daily report cron scheduler.
 * Uses node-cron to trigger report generation at midnight UTC every day.
 * Started once per server instance via /api/cron-initialize.
 */
import cron from "node-cron";
import { query } from "@/lib/db";

// Whether report is currently running (prevents overlap)
let isRunning = false;

async function runReport() {
  if (isRunning) {
    console.log("[daily-report-cron] Previous run still in progress, skipping");
    return;
  }
  isRunning = true;
  console.log("[daily-report-cron] Starting daily report generation at", new Date().toISOString());

  try {
    // Verify report is enabled
    const configRows = await query<{ config_key: string; config_value: string }>(
      `SELECT config_key, config_value FROM admin_ai_config WHERE config_key = 'report_enabled'`
    );
    const enabled = configRows.rows[0]?.config_value === "true";
    if (!enabled) {
      console.log("[daily-report-cron] Report disabled, skipping");
      return;
    }

    // Call generate endpoint internally (server-side fetch, no auth needed for cron)
    const baseUrl = process.env.NEXT_PUBLIC_APP_URL || `http://localhost:${process.env.PORT || 3000}`;
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      "x-cron-internal": "true",
    };
    if (process.env.DAILY_REPORT_CRON_SECRET) {
      headers["x-cron-secret"] = process.env.DAILY_REPORT_CRON_SECRET;
    }
    const res = await fetch(`${baseUrl}/api/admin/daily-report/generate`, {
      method: "POST",
      headers,
    });
    const data = await res.json().catch(() => ({}));
    console.log("[daily-report-cron] Result:", res.status, data);
  } catch (e) {
    console.error("[daily-report-cron] Error:", e);
  } finally {
    isRunning = false;
  }
}

let task: ReturnType<typeof cron.schedule> | null = null;

export function startDailyReportCron() {
  if (task) {
    console.log("[daily-report-cron] Already started");
    return;
  }

  // Run at midnight UTC every day
  task = cron.schedule("0 0 * * *", runReport, {
    timezone: "UTC",
  });

  console.log("[daily-report-cron] Scheduled: daily at 00:00 UTC");
}

export function stopDailyReportCron() {
  if (task) {
    task.stop();
    task = null;
    console.log("[daily-report-cron] Stopped");
  }
}
