/**
 * GET /api/ai-forecast?brandId=…
 *
 * Returns AI channel forecast with projections and what-if scenarios.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { generateAiForecast, runWhatIfScenarios } from "@/lib/intelligence/ai-forecasting";

export const dynamic = "force-dynamic";

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

  const url = new URL(req.url);
  const brandId = url.searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

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

  const months = parseInt(url.searchParams.get("months") ?? "6") || 6;

  const [forecast, scenarios] = await Promise.all([
    generateAiForecast(brandId, months),
    runWhatIfScenarios(brandId),
  ]);

  return NextResponse.json({ forecast, scenarios });
}
