import { NextResponse } from "next/server";
import { destroySession, getCurrentUser } from "@/lib/auth/session";
import { requireCsrf } from "@/lib/auth/csrf";
import { clientIp } from "@/lib/auth/rateLimit";
import {
  logSecurityEventAsync,
  SecurityEventType,
} from "@/lib/auth/securityEvents";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

export async function POST(request: Request) {
  const csrfBlocked = requireCsrf(request);
  if (csrfBlocked) return csrfBlocked;

  const ip = clientIp(request);
  const userAgent = request.headers.get("user-agent");

  // Capture who is signing out before the session is destroyed; a failed
  // lookup must not keep the user "stuck" signed in on the client.
  let userId: string | null = null;
  let email: string | null = null;
  try {
    const current = await getCurrentUser(request);
    if (current) {
      userId = current.id;
      email = current.email;
    }
  } catch {
    // Best-effort: logout proceeds even if the session lookup fails.
  }

  try {
    await destroySession(request);
  } catch (error) {
    // A failed lookup must not keep the user "stuck" signed in on the client.
    console.error("[auth] logout cleanup failed", error);
  }

  logSecurityEventAsync({
    type: SecurityEventType.LOGOUT,
    userId,
    email,
    ip,
    userAgent,
    metadata: { route: "/api/auth/logout" },
  });

  return NextResponse.json({ status: "signed_out" });
}
