import { NextResponse } from "next/server";

import { AUTH_COOKIE_NAME, getSessionCookieOptions } from "@/lib/auth";
import { createAuditTrailSafe } from "@/lib/audit-trail";
import { requireApiAccess } from "@/lib/authorization";

export async function POST(request: Request) {
  const auth = requireApiAccess(request);
  const response = NextResponse.json({
    message: "Logout berhasil"
  });

  response.cookies.set(AUTH_COOKIE_NAME, "", {
    ...getSessionCookieOptions(),
    maxAge: 0
  });

  await createAuditTrailSafe({
    userId: auth.ok ? auth.user.id : null,
    action: "LOGOUT",
    entityType: "AUTH",
    entityId: auth.ok ? auth.user.id : null,
    method: request.method,
    pathname: new URL(request.url).pathname,
    statusCode: 200,
    summary: "Logout berhasil"
  });

  return response;
}
