/**
 * PUT /api/gbp/locations/[id]/group — assign location to a group.
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function PUT(req: Request, { params }: { params: { id: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const body = await req.json().catch(() => null) as { groupName?: string } | null;
  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 });

  await prisma.gbpLocation.update({ where: { id: params.id }, data: { groupName: body?.groupName || null } });
  return NextResponse.json({ ok: true });
}
