/**
 * POST /api/gbp/sync-all — sync all locations for a brand.
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { syncMetrics, syncReviews } from "@/lib/services/gbp-multi-location";

export const dynamic = "force-dynamic";
export const maxDuration = 120;

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;
  if (!body?.brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const brand = await prisma.brand.findUnique({ where: { id: body.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 locations = await prisma.gbpLocation.findMany({ where: { brandId: body.brandId, isActive: true }, select: { id: true } });
  let totalMetrics = 0, totalReviews = 0;
  for (const loc of locations) {
    totalMetrics += await syncMetrics(loc.id, body.brandId, 30).catch(() => 0);
    totalReviews += await syncReviews(loc.id, body.brandId).catch(() => 0);
  }
  return NextResponse.json({ synced: locations.length, totalMetrics, totalReviews });
}
