/**
 * POST /api/performance-audit/compare-competitors
 * Body: { brandId }
 *
 * Scores the brand's homepage + up to 3 active competitor homepages
 * on PageSpeed (mobile strategy) and returns a side-by-side
 * comparison. Results are NOT persisted — this is an on-demand
 * point-in-time snapshot the UI renders inline.
 *
 * Wall budget 45s (see runCompetitorComparison) + 5s response
 * headroom → maxDuration 60s matches Vercel Pro baseline.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { runCompetitorComparison } from "@/lib/services/competitor-perf-comparison";

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;
  const brandId = body?.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: "Brand not found" }, { status: 404 });
  if (!brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const result = await runCompetitorComparison(brandId, brand.domain);
  return NextResponse.json(result);
}
