/**
 * GET /api/cron/ai-visibility — Weekly visibility audit for all brands.
 */
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { runVisibilityAudit } from "@/lib/services/ai-visibility-checker";

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

export async function GET(req: Request) {
  const secret = new URL(req.url).searchParams.get("secret");
  if (secret !== process.env.CRON_SECRET) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  // Find brands with active visibility queries
  const brands = await prisma.aiVisibilityQuery.findMany({
    where: { isActive: true },
    select: { brandId: true },
    distinct: ["brandId"],
  });

  const results: Array<{ brandId: string; score: number; error?: string }> = [];
  for (const { brandId } of brands) {
    try {
      const summary = await runVisibilityAudit(brandId);
      results.push({ brandId, score: summary.score });
    } catch (err) {
      results.push({ brandId, score: 0, error: err instanceof Error ? err.message : "Failed" });
    }
  }

  return NextResponse.json({ audited: results.length, results });
}
