import React, { useEffect } from 'react';
import { useAuthStore } from '@/features/auth/store/authStore';
import { authService } from '@/features/auth/services/authService';

interface AuthBootstrapProps {
  children: React.ReactNode;
}

export const AuthBootstrap: React.FC<AuthBootstrapProps> = ({ children }) => {
  useEffect(() => {
    let disposed = false;

    const hydrate = async () => {
      // Skip if user is already authenticated (e.g., just logged in)
      if (useAuthStore.getState().isAuthenticated) {
        useAuthStore.setState({ isLoading: false });
        return;
      }

      try {
        await authService.ensureCsrfCookie();
        const user = await authService.validateSession();

        if (disposed) {
          return;
        }

        if (user) {
          useAuthStore.getState().login(user);
        } else {
          useAuthStore.getState().logout();
        }
      } catch {
        if (!disposed) {
          useAuthStore.getState().logout();
        }
      } finally {
        if (!disposed) {
          useAuthStore.setState({ isLoading: false });
        }
      }
    };

    void hydrate();

    return () => {
      disposed = true;
    };
  }, []); // Empty dependency array - only run once on mount

  return <>{children}</>;
};
