/**
 * GET /api/cron/industry-intel — daily industry briefing generation.
 * Protected by CRON_SECRET.
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { generateBriefing, computeBenchmarks } from "@/lib/services/industry-intel";

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

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 });

  // Find all brands with industry set
  const brands = await prisma.brand.findMany({
    where: { isDemo: false, OR: [{ industry: { not: null } }, { profile: { industry: { not: null } } }] },
    select: { id: true, industry: true, domain: true },
    take: 100,
  });

  const results: Array<{ brandId: string; domain: string; success: boolean; error?: string }> = [];

  for (const brand of brands) {
    try {
      // Cron generates LOCAL briefings by default — that's the
      // primary view on the page now. National briefings are
      // generated on-demand when the user toggles the scope.
      const result = await generateBriefing(brand.id, { scope: "local" });
      results.push({ brandId: brand.id, domain: brand.domain, success: !!result });

      // Generate signals for critical events in the latest briefing
      if (result) {
        const briefing = await prisma.industryBriefing.findUnique({ where: { id: result.id }, select: { externalEvents: true, seasonalInsights: true } });
        const events = (briefing?.externalEvents as Array<{ severity?: string; title?: string; type?: string }>) ?? [];
        for (const ev of events) {
          if (ev.severity === "critical" || ev.severity === "major") {
            await prisma.siteEvent.create({
              data: {
                brandId: brand.id, pageUrl: brand.domain,
                eventType: ev.type === "weather" ? "weather_alert" : ev.type === "regulatory" ? "regulation_change" : "industry_event",
                eventData: { title: ev.title, severity: ev.severity, type: ev.type } as object,
              },
            }).catch(() => {}); // best effort
          }
        }
      }
    } catch (err) {
      results.push({ brandId: brand.id, domain: brand.domain, success: false, error: err instanceof Error ? err.message : "unknown" });
    }
  }

  // Compute benchmarks for active industries
  const industries = [...new Set(brands.map((b) => b.industry).filter(Boolean))];
  for (const ind of industries) {
    try { await computeBenchmarks(ind!); } catch { /* swallow */ }
  }

  return NextResponse.json({ processed: results.length, results, benchmarksComputed: industries.length });
}
