/**
 * GET /api/client-portal/report?brandId=X&days=28
 * Client-facing report data (same as report-studio but read-only).
 */

import { NextResponse } from "next/server";
import { requireClientAuth, pageAllowed } from "@/lib/client-auth";
import { generateBrandReport } from "@/lib/services/report-generator";

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

export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId") || "";
  const auth = await requireClientAuth(brandId);
  if (!auth.ok) return NextResponse.json({ error: auth.error }, { status: auth.status });
  if (!pageAllowed(auth.session, "report")) return NextResponse.json({ error: "Page not allowed" }, { status: 403 });

  const days = Math.max(7, Math.min(90, Number(searchParams.get("days") || 28)));
  const report = await generateBrandReport({ brandId, dateRange: days });

  return NextResponse.json({ report, portal: { agencyName: auth.session.agencyName } });
}
