/**
 * GET /api/cron/gbp-sync — daily GBP sync for all brands.
 * Protected by CRON_SECRET.
 */
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { syncMetrics, syncReviews } from "@/lib/services/gbp-multi-location";

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

const CRON_SECRET = process.env.CRON_SECRET ?? "";

function authOk(req: Request): boolean {
  if (!CRON_SECRET) return false;
  const header = req.headers.get("authorization") ?? "";
  if (header === `Bearer ${CRON_SECRET}`) return true;
  return new URL(req.url).searchParams.get("secret") === CRON_SECRET;
}

export async function GET(req: Request) {
  if (!authOk(req)) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const locations = await prisma.gbpLocation.findMany({
    where: { isActive: true },
    select: { id: true, brandId: true, locationName: true },
    take: 200,
  });

  const results: Array<{ location: string; metrics: number; reviews: number }> = [];

  for (const loc of locations) {
    try {
      const m = await syncMetrics(loc.id, loc.brandId, 7).catch(() => 0);
      const r = await syncReviews(loc.id, loc.brandId).catch(() => 0);
      results.push({ location: loc.locationName, metrics: m, reviews: r });

      // Generate signals for notable events
      const recentBad = await prisma.gbpReview.findFirst({
        where: { locationId: loc.id, rating: 1, publishedAt: { gte: new Date(Date.now() - 24 * 3600000) } },
      });
      if (recentBad) {
        await prisma.siteEvent.create({
          data: { brandId: loc.brandId, pageUrl: loc.locationName, eventType: "gbp_bad_review",
            eventData: { location: loc.locationName, rating: 1, reviewer: recentBad.reviewerName, comment: recentBad.comment?.slice(0, 200) } as object },
        }).catch(() => {});
      }

      const unreplied = await prisma.gbpReview.count({
        where: { locationId: loc.id, replyText: null, publishedAt: { gte: new Date(Date.now() - 48 * 3600000) } },
      });
      if (unreplied > 0) {
        await prisma.siteEvent.create({
          data: { brandId: loc.brandId, pageUrl: loc.locationName, eventType: "gbp_unreplied_reviews",
            eventData: { location: loc.locationName, count: unreplied, title: `${unreplied} unreplied reviews at ${loc.locationName}` } as object },
        }).catch(() => {});
      }
    } catch (err) {
      console.error(`[cron/gbp-sync] ${loc.locationName}`, err);
    }
  }

  return NextResponse.json({ synced: results.length, results });
}
