import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useAuthStore } from '../store/authStore';
import { getMe } from '@/services/api/auth';
// loginService removed as unused
import type { LoginRequest } from '@/services/api/auth';

export const useLogin = () => {
  const loginStore = useAuthStore((state) => state.login);
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (credentials: LoginRequest) => {
      // loginStore appelle déjà loginService et met à jour le store
      // Il attend aussi que la persistance soit complète
      await loginStore(credentials);

      // Vérifier que le store est bien mis à jour après la persistance
      const { isAuthenticated } = useAuthStore.getState();
      if (!isAuthenticated) {
        // Attendre un peu plus et réessayer
        await new Promise((resolve) => setTimeout(resolve, 100));
        const retryState = useAuthStore.getState();
        if (!retryState.isAuthenticated) {
          throw new Error(
            'Login failed: user not authenticated after persistence',
          );
        }
      }

      // Fetch user data and update React Query cache
      const user = await getMe();
      queryClient.setQueryData(['user', 'me'], user);
      
      return {
        user,
        isAuthenticated,
      };
    },
  });
};
