import { NextRequest, NextResponse } from "next/server";

import { getRequestAuditContext, writeAuditTrail } from "@/lib/audit";
import { getSession, SESSION_COOKIE } from "@/lib/auth";

export async function GET(request: NextRequest) {
  const session = await getSession();
  const { ipAddress, userAgent } = await getRequestAuditContext();

  if (session) {
    await writeAuditTrail({
      tenantId: session.tenantId,
      actorUserId: session.userId,
      entityType: "user",
      entityId: session.userId,
      action: "user_logout",
      metadata: { email: session.email },
      ipAddress,
      userAgent
    });
  }

  const response = NextResponse.redirect(new URL("/login", request.url));
  response.cookies.delete(SESSION_COOKIE);
  return response;
}
