"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 {
        // Mark that we're logging out to prevent auto-login
        sessionStorage.setItem('just_logged_out', 'true');
        
        // Get Keycloak issuer from environment
        const keycloakIssuer = process.env.NEXT_PUBLIC_KEYCLOAK_ISSUER;
        const idToken = session?.idToken;

        // First, sign out from NextAuth (clears NextAuth cookies)
        await signOut({ 
          callbackUrl: "/signin?logout=true",
          redirect: false 
        });

        // Clear NextAuth cookies client-side
        clearAuthCookies();

        // If we have Keycloak ID token and issuer, call Keycloak logout
        if (keycloakIssuer && idToken) {
          const keycloakLogoutUrl = new URL(
            `${keycloakIssuer}/protocol/openid-connect/logout`
          );
          
          // Add required parameters - include logout=true in redirect URI
          keycloakLogoutUrl.searchParams.append(
            'post_logout_redirect_uri',
            window.location.origin + '/signin?logout=true'
          );
          keycloakLogoutUrl.searchParams.append(
            'id_token_hint',
            idToken
          );
          
          // Redirect to Keycloak logout (this will clear Keycloak cookies)
          window.location.href = keycloakLogoutUrl.toString();
        } else {
          // Fallback: just redirect to signin if we don't have Keycloak info
          window.location.href = '/signin?logout=true';
        }
      } catch (error) {
        console.error('Error during sign out:', error);
        // Fallback: redirect to signin on error
        window.location.href = '/signin?logout=true';
      }
    };

    handleSignOut();
  }, [session]);

  return null;
} 