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

/**
 * GET /api/performance-audit?brandId=xxx&device=mobile&sort=lcp
 */
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");
  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 || !brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const audit = await getLatestPerfAudit(
    brandId,
    searchParams.get("device") ?? undefined,
    searchParams.get("sort") ?? undefined
  );

  return NextResponse.json(audit);
}

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

  try {
    const { brandId, device, pages } = await req.json();
    if (!brandId || !pages) return NextResponse.json({ error: "brandId and pages required" }, { status: 400 });
    const audit = await createPerfAudit(brandId, device || "mobile", pages);
    return NextResponse.json(audit, { status: 201 });
  } catch {
    return NextResponse.json({ error: "Something went wrong" }, { status: 500 });
  }
}
