import { NextResponse } from "next/server";
import { auth } from "@/auth";
import type { SessionUser } from "@/auth";

export async function GET() {
  const session = await auth();
  const user = session?.user as unknown as SessionUser | undefined;
  const idToken = user?.idToken;
  const issuer = process.env.AUTH_KEYCLOAK_ISSUER;
  const clientId = process.env.AUTH_KEYCLOAK_ID || "";
  const baseUrl = process.env.AUTH_URL || "http://localhost:3007";

  if (!issuer) {
    return NextResponse.json({ logoutUrl: `${baseUrl}/logged-out` });
  }

  const logoutUrl = new URL(`${issuer}/protocol/openid-connect/logout`);
  logoutUrl.searchParams.set("post_logout_redirect_uri", `${baseUrl}/logged-out`);
  logoutUrl.searchParams.set("client_id", clientId);
  if (idToken) {
    logoutUrl.searchParams.set("id_token_hint", idToken);
  }

  return NextResponse.json({ logoutUrl: logoutUrl.toString() });
}
