"use client";

import { useEffect } from "react";
import { signOut, useSession } from "next-auth/react";
import { clearAuthCookies } from "@/lib/session";

export function SignOutHandler() {
  const { data: session } = useSession();

  useEffect(() => {
    const handleSignOut = async () => {
      try {
        // Clear all auth-related cookies
        clearAuthCookies();
        
        // First sign out from NextAuth with redirect false
        await signOut({ 
          redirect: false 
        });
        
        // Then redirect to Keycloak logout with proper parameters
        if (process.env.NEXT_PUBLIC_KEYCLOAK_ISSUER) {
          const keycloakLogoutUrl = new URL(
            `${process.env.NEXT_PUBLIC_KEYCLOAK_ISSUER}/protocol/openid-connect/logout`
          );
          
          // Add required parameters
          keycloakLogoutUrl.searchParams.append(
            'post_logout_redirect_uri',
            `${window.location.origin}/signin?signedOut=true`
          );
          
          // Add id_token_hint if available
          if (session?.accessToken) {
            keycloakLogoutUrl.searchParams.append(
              'id_token_hint',
              session.accessToken
            );
          }
          
          // Redirect to Keycloak logout
          window.location.href = keycloakLogoutUrl.toString();
        } else {
          // Fallback if no Keycloak issuer is configured
          window.location.href = '/signin?signedOut=true';
        }
      } catch (error) {
        console.error('Error during logout:', error);
        // Fallback if something goes wrong
        window.location.href = '/signin?signedOut=true';
      }
    };

    handleSignOut();
  }, [session]);

  return null;
} 