/**
 * GET /api/admin/paid-media
 *
 * Cross-brand paid media overview. Uses the shared paid-media-metrics
 * service per brand then aggregates. Superadmin-only.
 */
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireSuperadmin, withAdminTiming } from "@/lib/admin-auth";
import {
  getChannelSummary,
  getVisitorProfileSummary,
  getHouseholdClusterSummary,
  getAdPlatformStatus,
} from "@/lib/services/paid-media-metrics";

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

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

  return NextResponse.json(await withAdminTiming("admin.paid-media", async () => {
    const d28 = new Date(Date.now() - 28 * 86_400_000);

    const sites = await prisma.trackedSite.findMany({
      where: { status: "active", firstEventAt: { not: null } },
      select: { brandId: true, brand: { select: { name: true, domain: true } } },
      take: 50,
    });

    const perBrand: Array<{
      brandId: string; name: string; domain: string;
      conversions: number; paidConversions: number; organicConversions: number;
      assistedConversions: number; visitors: number; clusters: number;
      connectedPlatforms: string[];
    }> = [];

    let totalConversions = 0;
    let totalPaid = 0;
    let totalOrganic = 0;
    let totalAssisted = 0;
    let totalVisitors = 0;
    let totalClusters = 0;
    let totalConnected = 0;

    for (const site of sites) {
      try {
        const [ch, vis, cl, plat] = await Promise.all([
          getChannelSummary(site.brandId, d28),
          getVisitorProfileSummary(site.brandId, d28),
          getHouseholdClusterSummary(site.brandId, d28),
          getAdPlatformStatus(site.brandId),
        ]);
        perBrand.push({
          brandId: site.brandId,
          name: site.brand.name,
          domain: site.brand.domain,
          conversions: ch.totalConversions,
          paidConversions: ch.paid.conversions,
          organicConversions: ch.organic.conversions,
          assistedConversions: ch.assisted.total,
          visitors: vis.total,
          clusters: cl.total,
          connectedPlatforms: plat.connected,
        });
        totalConversions += ch.totalConversions;
        totalPaid += ch.paid.conversions;
        totalOrganic += ch.organic.conversions;
        totalAssisted += ch.assisted.total;
        totalVisitors += vis.total;
        totalClusters += cl.total;
        totalConnected += plat.connected.length;
      } catch (err) {
        console.warn("[admin/paid-media] brand failed", {
          brandId: site.brandId,
          err: err instanceof Error ? err.message : String(err),
        });
      }
    }

    return {
      summary: {
        brands: perBrand.length,
        totalConversions,
        paidConversions: totalPaid,
        organicConversions: totalOrganic,
        assistedConversions: totalAssisted,
        visitorProfiles: totalVisitors,
        householdClusters: totalClusters,
        connectedPlatforms: totalConnected,
      },
      perBrand: perBrand.sort((a, b) => b.conversions - a.conversions),
    };
  }));
}
