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

export const dynamic = "force-dynamic";

/**
 * POST /api/admin/sessions/revoke-others
 * Terminates all active sessions for the current admin EXCEPT the current active session.
 */
export async function POST(req: NextRequest) {
  try {
    const { user, session: currentSession } = await requireAuth(req);
    const { ip, userAgent, location } = getClientMetadata(req);

    const revokedCount = await db.revokeOtherSessions(
      user.id,
      currentSession.tokenHash,
      user.email,
      "ADMIN_REVOKED"
    );

    // Audit log
    await db.logSecurityEvent({
      actorId: user.id,
      actorName: user.name,
      actorEmail: user.email,
      actorLevel: user.level,
      targetUserId: user.id,
      targetUserEmail: user.email,
      targetUserName: user.name,
      action: "SESSION_REVOKED",
      details: {
        revokedCount,
        preservedSessionId: currentSession.id,
        reason: "ADMIN_REVOKED",
        note: "Admin signed out all other devices",
      },
      ipAddress: ip,
      userAgent,
      location: location || currentSession.location,
    });

    return NextResponse.json({
      ok: true,
      revokedCount,
      message:
        revokedCount > 0
          ? `Successfully signed out ${revokedCount} other device${revokedCount === 1 ? "" : "s"}.`
          : "No other active sessions found.",
    });
  } catch (error) {
    const status = (error as unknown as { status: number }).status || 500;
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Failed to sign out other devices" },
      { status }
    );
  }
}
