/**
 * POST /api/report-studio/generate
 * Body: { brandId, dateRange?, sections? }
 *
 * Builds a structured BrandReport by aggregating GSC, GA4, Technical
 * Audit, Page Lifecycle, and AI Strategist data, then returns it to
 * the Report Studio UI. Auth: user must be a member of the brand's org.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import {
  generateBrandReport,
  type ReportSectionKey,
} from "@/lib/services/report-generator";
import { trackEvent } from "@/lib/services/platform-telemetry";

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

interface Body {
  brandId?: string;
  dateRange?: number;
  sections?: ReportSectionKey[];
}

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

  let body: Body;
  try { body = (await req.json()) as Body; }
  catch { return NextResponse.json({ error: "Invalid JSON" }, { status: 400 }); }

  const brandId = body.brandId;
  const dateRange = Number(body.dateRange) || 28;
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });
  if (dateRange < 1 || dateRange > 365) {
    return NextResponse.json({ error: "dateRange must be 1-365 days" }, { status: 400 });
  }

  // Permission check
  const brand = await prisma.brand.findUnique({
    where: { id: 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 });
  }

  try {
    const report = await generateBrandReport({
      brandId,
      dateRange,
      sections: body.sections,
    });
    // Engagement telemetry — fire-and-forget after the main work is done.
    trackEvent({
      userId: user.id,
      brandId,
      action: "generate_report",
      category: "content",
      metadata: { dateRange, sectionCount: body.sections?.length ?? null },
      request: req,
    });
    return NextResponse.json({ report });
  } catch (err) {
    const msg = err instanceof Error ? err.message : "Report generation failed";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
