/**
 * GET /api/gbp/locations/[id]/reviews?sort=recent&rating=all
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function GET(req: Request, { params }: { params: { id: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const loc = await prisma.gbpLocation.findUnique({ where: { id: params.id }, include: { brand: { include: { organization: { include: { memberships: true } } } } } });
  if (!loc) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (!loc.brand.organization.memberships.some((m) => m.userId === user.id)) return NextResponse.json({ error: "Access denied" }, { status: 403 });

  const { searchParams } = new URL(req.url);
  const rating = searchParams.get("rating");
  const where: Record<string, unknown> = { locationId: params.id };
  if (rating && rating !== "all") where.rating = Number(rating);

  const sort = searchParams.get("sort");
  const orderBy = sort === "rating" ? { rating: "desc" as const } : { publishedAt: "desc" as const };
  const reviews = await prisma.gbpReview.findMany({ where, orderBy, take: 50 });
  return NextResponse.json({ reviews });
}
