/**
 * GET /api/cron/ai-strategy-recommendations
 *
 * Daily cron that runs the AI Strategy Engine for all active brands.
 * Generates prioritised recommendations, runs auto-query expansion,
 * and triggers content brief detection.
 *
 * Schedule: "0 11 * * *" (daily at 11am UTC)
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { generateRecommendations } from "@/lib/intelligence/ai-strategy-engine";
import { expandConvertingQueries, expandFromCapturedQueries } from "@/lib/intelligence/auto-query-expansion";
import { detectBriefTriggers } from "@/lib/intelligence/content-brief-trigger";
import { logCron } from "@/lib/services/cron-logger";

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

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/ai-strategy-recommendations", async () => {
  const brands = await prisma.brand.findMany({
    where: { status: { not: "deleted" }, isDemo: false },
    select: { id: true, name: true },
  });

  const results: Record<string, {
    recommendations: number;
    queryExpansions: number;
    briefTriggers: number;
    error?: string;
  }> = {};

  for (const brand of brands) {
    try {
      const [recs, expanding, captured, briefs] = await Promise.allSettled([
        generateRecommendations(brand.id),
        expandConvertingQueries(brand.id),
        expandFromCapturedQueries(brand.id),
        detectBriefTriggers(brand.id),
      ]);

      results[brand.name] = {
        recommendations: recs.status === "fulfilled" ? recs.value.generated : 0,
        queryExpansions:
          (expanding.status === "fulfilled" ? expanding.value : 0) +
          (captured.status === "fulfilled" ? captured.value : 0),
        briefTriggers: briefs.status === "fulfilled" ? briefs.value : 0,
      };
    } catch (err) {
      results[brand.name] = {
        recommendations: 0,
        queryExpansions: 0,
        briefTriggers: 0,
        error: err instanceof Error ? err.message : String(err),
      };
    }
  }

  const payload = { brands: brands.length, results };
  return NextResponse.json(payload);
  });
}
