/**
 * GET /api/admin/export/growth-data
 *
 * Monthly growth time series for the data room. Per month going back
 * 24 months: newUsers (User.createdAt), newBrands (Brand.createdAt),
 * totalEvents (TrackedEvent.timestamp in month), totalSessions,
 * totalConversions, aiCalls (AiInteraction.timestamp), siteTagsDeployed
 * (TrackedSite.createdAt).
 *
 * Always CSV.
 *
 * Superadmin-only.
 */

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

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

const MONTHS_BACK = 24;

function monthBoundaries(monthsBack: number): Array<{ start: Date; end: Date; label: string }> {
  const out: Array<{ start: Date; end: Date; label: string }> = [];
  const now = new Date();
  for (let i = monthsBack - 1; i >= 0; i--) {
    const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - i, 1));
    const next = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1));
    out.push({
      start: d,
      end: next,
      label: `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}`,
    });
  }
  return out;
}

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

  return withAdminTiming("export.growth-data", async () => {
    const months = monthBoundaries(MONTHS_BACK);

    // Per-month aggregates run in parallel — one count per metric per
    // month. 24 months × 7 metrics = 168 cheap COUNT queries; each
    // hits an indexed timestamp column so total latency is dominated
    // by the connection pool throughput, not query cost. For very
    // large datasets a single SQL CTE would be cheaper; deferred
    // until volumes warrant it.
    const rows = await Promise.all(months.map(async (m) => {
      const [users, brands, events, sessions, conversions, aiCalls, siteTags] = await Promise.all([
        prisma.user.count({ where: { createdAt: { gte: m.start, lt: m.end } } }),
        prisma.brand.count({ where: { createdAt: { gte: m.start, lt: m.end } } }),
        prisma.trackedEvent.count({ where: { timestamp: { gte: m.start, lt: m.end } } }),
        prisma.trackedSession.count({ where: { startedAt: { gte: m.start, lt: m.end } } }),
        // intentionally unfiltered: admin-only endpoint; needs raw or all-time counts
        prisma.siteConversion.count({ where: { timestamp: { gte: m.start, lt: m.end } } }),
        prisma.aiInteraction.count({ where: { timestamp: { gte: m.start, lt: m.end } } }),
        prisma.trackedSite.count({ where: { createdAt: { gte: m.start, lt: m.end } } }),
      ]);
      return { month: m.label, users, brands, events, sessions, conversions, aiCalls, siteTags };
    }));

    const headers = ["month", "newUsers", "newBrands", "totalEvents", "totalSessions", "totalConversions", "aiCalls", "siteTagsDeployed"];
    const csvRows = rows.map((r) => [r.month, r.users, r.brands, r.events, r.sessions, r.conversions, r.aiCalls, r.siteTags]);
    const csv = toCsv(headers, csvRows);
    return new NextResponse(csv, {
      status: 200,
      headers: {
        "Content-Type": "text/csv",
        "Content-Disposition": `attachment; filename="growth-timeseries-${new Date().toISOString().slice(0, 10)}.csv"`,
      },
    });
  });
}
