import { auth, signOut } from "@/auth";

// RP-initiated logout. Overrides NextAuth's default /api/auth/signout
// confirmation page: kills both the NextAuth cookie and the Keycloak
// SSO session, then bounces to /signed-out.

async function handleSignout(request: Request): Promise<Response> {
  const session = await auth();
  const idToken = (session?.user as { idToken?: string } | undefined)?.idToken;

  await signOut({ redirect: false });

  const issuer = process.env.AUTH_KEYCLOAK_ISSUER;
  const origin = (
    process.env.AUTH_URL ??
    process.env.NEXTAUTH_URL ??
    new URL(request.url).origin
  ).replace(/\/$/, "");
  const postLogout = `${origin}/signed-out`;

  if (!issuer) return Response.redirect(postLogout, 302);

  const endSession = new URL(`${issuer}/protocol/openid-connect/logout`);
  endSession.searchParams.set("post_logout_redirect_uri", postLogout);
  if (idToken) endSession.searchParams.set("id_token_hint", idToken);
  else endSession.searchParams.set("client_id", process.env.AUTH_KEYCLOAK_ID ?? "");
  return Response.redirect(endSession.toString(), 302);
}

export const GET = handleSignout;
export const POST = handleSignout;
