/**
 * POST /api/industry-intel/correlate
 * Returns performance correlations with external events.
 * Used by AI Strategist + Dashboard for normalized performance overlay.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { gatherBrandContext, correlatePerformance } from "@/lib/services/industry-intel";

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

export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json().catch(() => null) as { brandId?: string } | null;
  if (!body?.brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const brand = await prisma.brand.findUnique({
    where: { id: body.brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });
  if (!brand.organization.memberships.some((m) => m.userId === user.id)) return NextResponse.json({ error: "Access denied" }, { status: 403 });

  const ctx = await gatherBrandContext(body.brandId);
  if (!ctx) return NextResponse.json({ error: "Brand has no industry set" }, { status: 400 });

  // Get latest briefing's external events
  const briefing = await prisma.industryBriefing.findFirst({
    where: { brandId: body.brandId },
    orderBy: { generatedAt: "desc" },
    select: { externalEvents: true },
  });
  const events = (briefing?.externalEvents as unknown[]) ?? [];
  const correlations = await correlatePerformance(ctx, events);

  return NextResponse.json({ correlations });
}
