/**
 * POST   /api/admin/users/[userId]/suspend     — ban via Clerk
 * DELETE /api/admin/users/[userId]/suspend     — un-ban via Clerk
 *
 * Suspension is enforced at the Clerk layer (clerkClient.users.banUser
 * / unbanUser). A banned user can't sign in until unbanned, which is
 * the strongest reversible action available without a destructive
 * delete. Any side-effects (signing them out of active sessions) are
 * Clerk's responsibility.
 *
 * Logged to ComplianceEvent so the admin Compliance dashboard sees
 * suspend/reactivate as a regulatory-relevant trail.
 *
 * Superadmin-only.
 */

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

export const dynamic = "force-dynamic";

export async function POST(_req: Request, ctx: { params: { userId: string } }) {
  return runAction(ctx.params.userId, "suspend");
}

export async function DELETE(_req: Request, ctx: { params: { userId: string } }) {
  return runAction(ctx.params.userId, "reactivate");
}

async function runAction(userId: string, kind: "suspend" | "reactivate") {
  const denied = await requireSuperadmin();
  if (denied) return denied;
  const admin = await getSuperadmin();
  if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  if (admin.userId === userId) {
    return NextResponse.json({ error: "Cannot suspend your own account" }, { status: 400 });
  }

  return NextResponse.json(await withAdminTiming(`users.${kind}`, async () => {
    try {
      const clerk = await clerkClient();
      if (kind === "suspend") {
        await clerk.users.banUser(userId);
      } else {
        await clerk.users.unbanUser(userId);
      }
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Clerk action failed";
      return { ok: false as const, error: msg };
    }

    // Audit the suspend / reactivate so the regulatory log is
    // complete. action keys are stable for downstream filtering.
    await prisma.complianceEvent.create({
      data: {
        action: kind === "suspend" ? "user_suspended" : "user_reactivated",
        identifier: userId,
        details: {} as object,
        requestedBy: admin.userId,
      },
    }).catch(() => {});

    return { ok: true as const };
  }));
}
