/**
 * POST /api/admin/debug/backfill-snapshots[?brandId=xxx]
 *
 * Populates MetricSnapshot rows from existing GscPage + GscQuery
 * daily data. Runs per-brand, upserts one MetricSnapshot per day
 * with source="gsc". Fills the Historical Tracking page's monthly
 * trend view with real per-day GSC data going back to the earliest
 * GscPage record.
 *
 * Safe to call repeatedly — upserts by (brandId, date, source).
 * Superadmin-only. maxDuration=300 because large brands may have
 * 500+ distinct dates.
 */
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireSuperadmin } from "@/lib/admin-auth";

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

export async function POST(req: Request) {
  const denied = await requireSuperadmin();
  if (denied) return denied;

  const targetBrandId = new URL(req.url).searchParams.get("brandId");
  const brands = await prisma.brand.findMany({
    where: targetBrandId ? { id: targetBrandId } : {},
    select: { id: true, name: true },
  });

  const results: Record<string, { days: number; created: number; errors: number }> = {};

  for (const brand of brands) {
    const row = { days: 0, created: 0, errors: 0 };
    results[brand.name] = row;

    // Get all distinct dates from GscPage for this brand
    const dateBuckets = await prisma.gscPage.groupBy({
      by: ["date"],
      where: { brandId: brand.id },
      _sum: { clicks: true, impressions: true },
      _avg: { position: true, ctr: true },
      orderBy: { date: "asc" },
    }).catch(() => []);

    row.days = dateBuckets.length;

    for (const bucket of dateBuckets) {
      try {
        await prisma.metricSnapshot.upsert({
          where: { brandId_date_source: { brandId: brand.id, date: bucket.date, source: "gsc" } },
          create: {
            brandId: brand.id,
            date: bucket.date,
            source: "gsc",
            organicClicks: bucket._sum.clicks ?? 0,
            impressions: bucket._sum.impressions ?? 0,
            avgPosition: Math.round((bucket._avg.position ?? 0) * 10) / 10,
            ctr: Math.round((bucket._avg.ctr ?? 0) * 10000) / 10000,
          },
          update: {
            organicClicks: bucket._sum.clicks ?? 0,
            impressions: bucket._sum.impressions ?? 0,
            avgPosition: Math.round((bucket._avg.position ?? 0) * 10) / 10,
            ctr: Math.round((bucket._avg.ctr ?? 0) * 10000) / 10000,
          },
        });
        row.created++;
      } catch {
        row.errors++;
      }
    }

    console.info(`[backfill-snapshots] ${brand.name}: ${row.days} days, ${row.created} created, ${row.errors} errors`);
  }

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