/**
 * GET /api/admin/compliance/events
 *
 * Paginated ComplianceEvent log + CSV export.
 *
 * Query params:
 *   page, limit (default 50, max 200)
 *   action      — optional filter
 *   format=csv  — returns text/csv attachment instead of JSON
 *
 * Superadmin-only.
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireSuperadmin, withAdminTiming } from "@/lib/admin-auth";
import type { Prisma } from "@prisma/client";

export const dynamic = "force-dynamic";

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

  const { searchParams } = new URL(req.url);
  const format = searchParams.get("format");
  const page = Math.max(1, Number(searchParams.get("page") ?? 1));
  const limit = format === "csv"
    ? 5000  // CSV exports take the full set up to a hard cap
    : Math.max(1, Math.min(200, Number(searchParams.get("limit") ?? 50)));
  const skip = (page - 1) * limit;
  const action = searchParams.get("action") ?? "";

  return withAdminTiming("compliance.events", async () => {
    const where: Prisma.ComplianceEventWhereInput = {};
    if (action) where.action = action;

    const [rows, total] = await Promise.all([
      prisma.complianceEvent.findMany({
        where,
        orderBy: { timestamp: "desc" },
        skip: format === "csv" ? 0 : skip,
        take: limit,
      }),
      prisma.complianceEvent.count({ where }),
    ]);

    if (format === "csv") {
      const header = ["timestamp", "action", "brandId", "identifier", "requestedBy", "details"];
      const lines = rows.map((r) => [
        r.timestamp.toISOString(),
        r.action,
        r.brandId ?? "",
        r.identifier ?? "",
        r.requestedBy,
        JSON.stringify(r.details ?? {}),
      ].map((c) => `"${String(c).replace(/"/g, '""')}"`).join(","));
      const csv = [header.join(","), ...lines].join("\n");
      return new NextResponse(csv, {
        status: 200,
        headers: {
          "Content-Type": "text/csv",
          "Content-Disposition": `attachment; filename="compliance-events-${new Date().toISOString().slice(0, 10)}.csv"`,
        },
      });
    }

    return NextResponse.json({
      rows: rows.map((r) => ({ ...r, timestamp: r.timestamp.toISOString() })),
      total, page, limit,
      hasMore: skip + rows.length < total,
    });
  });
}
