/**
 * @ai-summary Custom logout hook with audit logging
 * @ai-context Tracks logout event before Auth0 logout for audit trail
 */

import { useAuth0 } from '@auth0/auth0-react';
import { useCallback } from 'react';

/**
 * Custom hook that wraps Auth0 logout with audit tracking.
 * Calls /api/auth/track-logout before performing Auth0 logout.
 * The audit call is fire-and-forget to ensure logout always completes.
 */
export const useLogout = () => {
  const { logout: auth0Logout, getAccessTokenSilently } = useAuth0();

  const logout = useCallback(async () => {
    // Fire-and-forget audit call (don't block logout)
    try {
      const token = await getAccessTokenSilently({ cacheMode: 'on' as const });
      if (token) {
        // Use fetch directly to avoid axios interceptor issues during logout
        fetch('/api/auth/track-logout', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
        }).catch(() => {
          // Silently ignore errors - don't block logout
        });
      }
    } catch {
      // Token not available - proceed with logout anyway
    }

    // Perform Auth0 logout
    auth0Logout({
      logoutParams: {
        returnTo: window.location.origin,
      },
    });
  }, [auth0Logout, getAccessTokenSilently]);

  return { logout };
};
