/**
 * GET /api/cron/brand-health
 *
 * Hourly cron that checks every active brand's Site Tag event rate
 * against its 7-day same-hour baseline. Fires an email alert when
 * a brand has been degraded (≥90% drop) for 2+ consecutive hours.
 * Auto-resolves when the rate returns to >50% of expected.
 *
 * Schedule: "0 * * * *" (every hour on the hour)
 */

import { NextResponse } from "next/server";
import { logCron } from "@/lib/services/cron-logger";
import { runBrandHealthCheck } from "@/lib/services/brand-health-detector";

export const dynamic = "force-dynamic";
export const maxDuration = 180;

export async function GET(req: Request) {
  const cronSecret = process.env.CRON_SECRET;
  if (!cronSecret) {
    return NextResponse.json({ error: "Server misconfigured: CRON_SECRET unset" }, { status: 500 });
  }
  const authHeader = req.headers.get("authorization");
  const querySecret = new URL(req.url).searchParams.get("secret");
  if (authHeader !== `Bearer ${cronSecret}` && querySecret !== cronSecret) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  return logCron("/api/cron/brand-health", async () => {
    const results = await runBrandHealthCheck();

    const summary = {
      total: results.length,
      skipped: results.filter((r) => r.skipped).length,
      healthy: results.filter((r) => !r.skipped && r.action === "none").length,
      opened: results.filter((r) => r.action === "opened").length,
      escalatedToDown: results.filter((r) => r.action === "escalated_to_down").length,
      resolved: results.filter((r) => r.action === "resolved").length,
      updated: results.filter((r) => r.action === "updated").length,
    };

    console.log("[brand-health] run complete", summary);
    return NextResponse.json({ ok: true, summary, results });
  });
}
