import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/admin/db";
import { requireMainAdmin, getClientMetadata } from "@/lib/admin/auth";

export const dynamic = "force-dynamic";

export async function POST(
  req: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { user: mainAdmin } = await requireMainAdmin(req);
    const { ip } = getClientMetadata(req);
    const { id } = await context.params;

    const target = await db.getUserById(id);
    if (!target) {
      return NextResponse.json({ error: "Administrator not found." }, { status: 404 });
    }

    const body = await req.json().catch(() => ({}));
    const reason = body.reason || "Forced logout initiated by Main Administrator";

    const revokedCount = await db.revokeAllSessionsForUser(
      target.id,
      mainAdmin.email,
      reason
    );

    await db.logSecurityEvent({
      actorId: mainAdmin.id,
      actorName: mainAdmin.name,
      actorEmail: mainAdmin.email,
      actorLevel: mainAdmin.level,
      targetUserId: target.id,
      targetUserEmail: target.email,
      targetUserName: target.name,
      action: "FORCE_LOGOUT_ALL",
      details: {
        revokedSessionsCount: revokedCount,
        reason,
      },
      ipAddress: ip,
    });

    return NextResponse.json({
      ok: true,
      revokedCount,
      message: `Successfully revoked ${revokedCount} active session${revokedCount === 1 ? "" : "s"} for ${target.name}.`,
    });
  } catch (error) {
    const status = (error as unknown as { status: number }).status || 500;
    return NextResponse.json(
      { error: (error as Error).message || "Failed to force logout administrator." },
      { status }
    );
  }
}
