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

export const dynamic = "force-dynamic";

/**
 * POST /api/admin/auth/lock
 * Marks the active admin session as locked due to inactivity.
 */
export async function POST(req: NextRequest) {
  try {
    const rawToken = await extractRawToken(req);
    const ctx = await getAdminSession(req);
    if (!ctx || !rawToken) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const tokenHash = hashToken(rawToken);
    await db.lockSession(tokenHash);

    const { ip } = getClientMetadata(req);
    await db.logSecurityEvent({
      actorId: ctx.user.id,
      actorName: ctx.user.name,
      actorEmail: ctx.user.email,
      actorLevel: ctx.user.level,
      targetUserId: ctx.user.id,
      targetUserEmail: ctx.user.email,
      targetUserName: ctx.user.name,
      action: "SESSION_LOCKED",
      details: { reason: "5-minute idle inactivity lock" },
      ipAddress: ip,
    });

    return NextResponse.json({ ok: true, isLocked: true });
  } catch (err: any) {
    console.error("[POST /api/admin/auth/lock] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to lock session." },
      { status: 500 }
    );
  }
}
