import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { comparePages } from "@/lib/services/performance-audit";

/**
 * GET /api/performance-audit/compare?brandId=xxx&pageA=/pricing&pageB=/blog&device=mobile
 *
 * Returns side-by-side comparison of two pages:
 * - Scores: performance, accessibility, best practices, SEO
 * - Vitals: LCP, INP, CLS, FCP, TTFB
 * - Per-metric winner
 * - Overall summary with win counts
 */
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 { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");
  const pageA = searchParams.get("pageA");
  const pageB = searchParams.get("pageB");
  const device = searchParams.get("device") || "mobile";

  if (!brandId || !pageA || !pageB) {
    return NextResponse.json({ error: "brandId, pageA, and pageB are required" }, { status: 400 });
  }

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

  const result = await comparePages(brandId, pageA, pageB, device);

  if (!result) {
    return NextResponse.json({ error: "One or both pages not found in the latest audit" }, { status: 404 });
  }

  return NextResponse.json(result);
}
