/**
 * GET /api/cron/check-alerts — hourly alert condition checks.
 */
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { checkAlertConditions } from "@/lib/services/notification-service";

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

const CRON_SECRET = process.env.CRON_SECRET ?? "";

function authOk(req: Request): boolean {
  if (!CRON_SECRET) return false;
  const header = req.headers.get("authorization") ?? "";
  if (header === `Bearer ${CRON_SECRET}`) return true;
  return new URL(req.url).searchParams.get("secret") === CRON_SECRET;
}

export async function GET(req: Request) {
  if (!authOk(req)) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const brands = await prisma.alertRule.findMany({ where: { isActive: true }, select: { brandId: true }, distinct: ["brandId"] });
  const results: Array<{ brandId: string; fired: number }> = [];

  for (const { brandId } of brands) {
    try {
      const fired = await checkAlertConditions(brandId);
      results.push({ brandId, fired });
    } catch (err) { console.error(`[cron/alerts] ${brandId}`, err); }
  }

  return NextResponse.json({ checked: results.length, totalFired: results.reduce((s, r) => s + r.fired, 0), results });
}
