/**
 * GET /api/admin/debug-ga4?brandId=…
 *
 * Diagnostic endpoint that traces the full GA4 data path for a brand:
 * MetricSnapshot records, missing dates, integration status, daily
 * chart source, and ConversionEvent records.
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireSuperadmin } from "@/lib/admin-auth";

export const dynamic = "force-dynamic";

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

  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 },
    select: { id: true, name: true, domain: true },
  });
  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });

  // 1. All MetricSnapshot records (last 60 days)
  const d60 = new Date(Date.now() - 60 * 86_400_000);
  const snapshots = await prisma.metricSnapshot.findMany({
    where: { brandId, date: { gte: d60 } },
    orderBy: { date: "desc" },
    select: { date: true, source: true, sessions: true, users: true, pageviews: true, conversions: true, revenue: true },
  }).catch(() => []);

  // 2. Which dates have records and which don't
  const last30 = Array.from({ length: 30 }, (_, i) => {
    const d = new Date();
    d.setDate(d.getDate() - i);
    return d.toISOString().split("T")[0];
  });
  const existingDates = new Set(snapshots.map((s) => s.date.toISOString().split("T")[0]));
  const missingDates = last30.filter((d) => !existingDates.has(d));

  // 3. GA4 integration status
  const integration = await prisma.brandIntegration.findFirst({
    where: { brandId, integrationId: "ga4" },
    select: {
      id: true,
      connected: true,
      lastSynced: true,
      createdAt: true,
    },
  }).catch(() => null);

  // 4. ConversionEvent records (the other possible chart source)
  const convEvents = await prisma.conversionEvent.findMany({
    where: { brandId, date: { gte: d60 } },
    orderBy: { date: "desc" },
    take: 60,
    select: { date: true, type: true, value: true, source: true },
  }).catch(() => []);

  // 5. Daily chart data — aggregate MetricSnapshot by date
  const dailyFromSnapshots: Record<string, { sessions: number; conversions: number; revenue: number }> = {};
  for (const s of snapshots) {
    const key = s.date.toISOString().split("T")[0];
    const entry = dailyFromSnapshots[key] ?? { sessions: 0, conversions: 0, revenue: 0 };
    entry.sessions += s.sessions;
    entry.conversions += s.conversions;
    entry.revenue += s.revenue;
    dailyFromSnapshots[key] = entry;
  }

  // 6. Daily chart data from ConversionEvent
  const dailyFromEvents: Record<string, { count: number; value: number }> = {};
  for (const e of convEvents) {
    const key = e.date.toISOString().split("T")[0];
    const entry = dailyFromEvents[key] ?? { count: 0, value: 0 };
    entry.count += 1;
    entry.value += e.value;
    dailyFromEvents[key] = entry;
  }

  return NextResponse.json({
    brand: { id: brand.id, name: brand.name, domain: brand.domain },
    integration: integration ?? "NOT FOUND",
    summary: {
      totalSnapshots: snapshots.length,
      datesWithData: existingDates.size,
      missingDates,
      missingCount: missingDates.length,
      snapshotSources: [...new Set(snapshots.map((s) => s.source))],
      convEventCount: convEvents.length,
      convEventSources: [...new Set(convEvents.map((e) => e.source))],
    },
    snapshots: snapshots.slice(0, 30).map((s) => ({
      date: s.date.toISOString().split("T")[0],
      source: s.source,
      sessions: s.sessions,
      conversions: s.conversions,
      revenue: s.revenue,
    })),
    convEvents: convEvents.slice(0, 30).map((e) => ({
      date: e.date.toISOString().split("T")[0],
      type: e.type,
      value: e.value,
      source: e.source,
    })),
    dailyFromSnapshots,
    dailyFromEvents,
    // What the chart would render for the last 30 days:
    chartPreview: last30.reverse().map((d) => ({
      date: d,
      snapshotConversions: dailyFromSnapshots[d]?.conversions ?? null,
      eventConversions: dailyFromEvents[d]?.count ?? null,
      hasData: existingDates.has(d),
    })),
  });
}
