import { useEffect } from 'react';
import { useIsAuthenticated } from './auth.store';
import { useTenantActions, useAvailableTenants } from './tenant.store';

/**
 * Hook to automatically initialize tenant data when user is authenticated
 * This should be used at the app level to ensure tenant data is loaded
 */
export const useTenantInitializer = () => {
  const isAuthenticated = useIsAuthenticated();
  const availableTenants = useAvailableTenants();
  const { loadUserTenants } = useTenantActions();

  useEffect(() => {
    if (isAuthenticated && !availableTenants) {
      // Load user's available tenants when authenticated and not already loaded
      loadUserTenants();
    }
  }, [isAuthenticated, availableTenants, loadUserTenants]);

  // Also load tenants when user becomes authenticated (e.g., after login)
  useEffect(() => {
    if (isAuthenticated && availableTenants === null) {
      loadUserTenants();
    }
  }, [isAuthenticated, availableTenants, loadUserTenants]);
};