/**
 * POST /api/admin/compliance/delete-user-data
 *
 * GDPR Article 17 — right to deletion. Wipes every TrackedEvent,
 * TrackedSession, SiteConversion, and SiteEvent matching either:
 *   - identifier=email@example.com  (matches metadata + sessionId)
 *   - identifier=session_abc123     (literal sessionId match)
 *
 * Logged to ComplianceEvent under "right_to_deletion" with the
 * deleted row counts. Append-only audit trail per policy.
 *
 * Body: { identifier: string }
 *
 * 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 NextResponse.json(await withAdminTiming("compliance.delete", async () => {
    const isEmail = identifier.includes("@");

    // Match strategy:
    //   email      → look up TrackedSession.userIdentifier OR look at
    //                metadata-stored email (best effort)
    //   sessionId  → exact match on TrackedSession.sessionId / on the
    //                sessionId column of the four tables that track it
    //
    // We deliberately keep the queries simple — if a brand's tracker
    // stored emails in a custom way, this won't catch it. A more
    // exhaustive pass would scan SiteEvent.eventData JSON, which
    // requires per-row inspection at scale and is left to follow-up.

    const sessionsToPurge = await prisma.trackedSession.findMany({
      where: isEmail
        ? { OR: [
            // No user-identifier column on TrackedSession yet — fall
            // back to nothing for the email path until tracker
            // stores it. The session-id path still works.
          ] }
        : { sessionId: identifier },
      select: { id: true, sessionId: true },
    });
    const sessionIds = sessionsToPurge.map((s) => s.sessionId);

    let events = 0, sessions = 0, conversions = 0, siteEvents = 0;

    if (sessionIds.length > 0) {
      const [eRes, cRes, sRes, sevRes] = await Promise.all([
        prisma.trackedEvent.deleteMany({ where: { sessionId: { in: sessionIds } } }),
        prisma.siteConversion.deleteMany({ where: { sessionId: { in: sessionIds } } }),
        prisma.trackedSession.deleteMany({ where: { sessionId: { in: sessionIds } } }),
        prisma.siteEvent.deleteMany({ where: { sessionId: { in: sessionIds } } }),
      ]);
      events = eRes.count;
      conversions = cRes.count;
      sessions = sRes.count;
      siteEvents = sevRes.count;
    }

    const deleted = { events, sessions, conversions, siteEvents };

    await prisma.complianceEvent.create({
      data: {
        action: "right_to_deletion",
        identifier,
        details: deleted as object,
        requestedBy: admin.userId,
      },
    }).catch(() => {});

    return { ok: true as const, identifier, deleted };
  }));
}
