/**
 * GET /api/gbp/locations?brandId=X&group=&sort=views
 * List locations with latest metric summary.
 */
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) {
  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) 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 where: Record<string, unknown> = { brandId, isActive: true };
  const group = searchParams.get("group");
  if (group) where.groupName = group;

  const locations = await prisma.gbpLocation.findMany({
    where,
    include: {
      metrics: { orderBy: { date: "desc" }, take: 30 },
      _count: { select: { reviews: true } },
    },
    orderBy: { locationName: "asc" },
  });

  const result = locations.map((loc) => {
    const last30 = loc.metrics;
    const sum = (key: keyof typeof last30[0]) => last30.reduce((s, m) => s + (Number(m[key]) || 0), 0);
    return {
      ...loc, metrics: undefined,
      metricSummary: { views: sum("viewsTotal"), websiteClicks: sum("websiteClicks"), phoneClicks: sum("phoneClicks"), directionClicks: sum("directionClicks") },
      reviewCount: loc._count.reviews,
    };
  });

  const sort = searchParams.get("sort");
  if (sort === "views") result.sort((a, b) => b.metricSummary.views - a.metricSummary.views);
  else if (sort === "calls") result.sort((a, b) => b.metricSummary.phoneClicks - a.metricSummary.phoneClicks);
  else if (sort === "reviews") result.sort((a, b) => b.reviewCount - a.reviewCount);

  return NextResponse.json({ locations: result });
}
