/**
 * GET /api/gbp/overview?brandId=X — aggregated overview across all locations.
 */
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 brandId = new URL(req.url).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 locations = await prisma.gbpLocation.findMany({ where: { brandId, isActive: true }, select: { id: true, locationName: true, avgRating: true, totalReviews: true, groupName: true } });
  const locationIds = locations.map((l) => l.id);
  const d30 = new Date(Date.now() - 30 * 86400000);

  const [metricsAgg, unreplied, totalReviewCount] = await Promise.all([
    prisma.gbpMetric.aggregate({ where: { locationId: { in: locationIds }, date: { gte: d30 } }, _sum: { viewsTotal: true, websiteClicks: true, phoneClicks: true, directionClicks: true } }),
    prisma.gbpReview.count({ where: { locationId: { in: locationIds }, replyText: null, publishedAt: { gte: new Date(Date.now() - 48 * 3600000) } } }),
    prisma.gbpReview.count({ where: { locationId: { in: locationIds } } }),
  ]);

  const avgRating = locations.length > 0 ? locations.reduce((s, l) => s + l.avgRating, 0) / locations.length : 0;
  const best = locations.reduce((b, l) => l.avgRating > (b?.avgRating ?? 0) ? l : b, locations[0]);
  const worst = locations.reduce((w, l) => l.avgRating < (w?.avgRating ?? 6) ? l : w, locations[0]);

  return NextResponse.json({
    locationCount: locations.length,
    totalViews: metricsAgg._sum.viewsTotal ?? 0,
    totalWebsiteClicks: metricsAgg._sum.websiteClicks ?? 0,
    totalPhoneClicks: metricsAgg._sum.phoneClicks ?? 0,
    totalDirectionClicks: metricsAgg._sum.directionClicks ?? 0,
    avgRating: Math.round(avgRating * 10) / 10,
    totalReviews: totalReviewCount,
    unrepliedReviews: unreplied,
    bestLocation: best ? { name: best.locationName, rating: best.avgRating } : null,
    worstLocation: worst ? { name: worst.locationName, rating: worst.avgRating } : null,
    groups: [...new Set(locations.map((l) => l.groupName).filter(Boolean))],
  });
}
