/**
 * POST /api/admin/compliance/export-user-data
 *
 * GDPR Article 15 — right of access. Returns a JSON dump of every
 * TrackedEvent, TrackedSession, SiteConversion, and SiteEvent
 * matching the identifier (email or sessionId).
 *
 * Body: { identifier: string }
 *
 * Logged to ComplianceEvent under "data_export".
 *
 * Superadmin-only.
 */

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

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

export async function POST(req: Request) {
  const denied = await requireSuperadmin();
  if (denied) return denied;
  const admin = await getSuperadmin();
  if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const body = await req.json().catch(() => null) as { identifier?: string } | null;
  const identifier = body?.identifier?.trim();
  if (!identifier) return NextResponse.json({ error: "identifier required" }, { status: 400 });

  return withAdminTiming("compliance.export", async () => {
    const isEmail = identifier.includes("@");

    // Same matching strategy as delete-user-data — scoped to
    // TrackedSession.sessionId for now. A future revision can add
    // cross-table email scanning once the tracker captures it
    // explicitly.
    const sessions = isEmail
      ? []
      : await prisma.trackedSession.findMany({ where: { sessionId: identifier } });
    const sessionIds = sessions.map((s) => s.sessionId);

    const [events, conversions, siteEvents] = sessionIds.length > 0
      ? await Promise.all([
          prisma.trackedEvent.findMany({ where: { sessionId: { in: sessionIds } } }),
          // intentionally unfiltered: admin-only endpoint; needs raw or all-time counts
          prisma.siteConversion.findMany({ where: { sessionId: { in: sessionIds } } }),
          prisma.siteEvent.findMany({ where: { sessionId: { in: sessionIds } } }),
        ])
      : [[], [], []];

    const payload = {
      exportedAt: new Date().toISOString(),
      identifier,
      counts: {
        events: events.length,
        sessions: sessions.length,
        conversions: conversions.length,
        siteEvents: siteEvents.length,
      },
      data: {
        sessions,
        events,
        conversions,
        siteEvents,
      },
    };

    // Audit log — the export itself is sensitive enough that the
    // act of exporting needs to be tracked even when the data is
    // delivered to the data subject.
    await prisma.complianceEvent.create({
      data: {
        action: "data_export",
        identifier,
        details: payload.counts as object,
        requestedBy: admin.userId,
      },
    }).catch(() => {});

    // Stream as a download attachment.
    return new NextResponse(JSON.stringify(payload, null, 2), {
      status: 200,
      headers: {
        "Content-Type": "application/json",
        "Content-Disposition": `attachment; filename="user-data-${identifier.replace(/[^a-z0-9._-]/gi, "_")}.json"`,
      },
    });
  });
}
