import { useQuery } from '@tanstack/react-query';
import { useAuth0 } from '@auth0/auth0-react';
import { fuelLogsApi } from '../api/fuel-logs.api';
import { FuelType, FuelGradeOption } from '../types/fuel-logs.types';

export const useFuelGrades = (fuelType: FuelType) => {
  const { isAuthenticated, isLoading: authLoading } = useAuth0();
  const { data, isLoading, error } = useQuery<FuelGradeOption[]>({
    queryKey: ['fuelGrades', fuelType],
    queryFn: () => fuelLogsApi.getFuelGrades(fuelType),
    enabled: isAuthenticated && !authLoading,
    retry: (failureCount, error: any) => {
      // Retry 401 errors up to 3 times for mobile auth timing issues
      if (error?.response?.status === 401 && failureCount < 3) {
        console.log(`[Mobile Auth] Fuel grades API retry ${failureCount + 1}/3 for 401 error`);
        return true;
      }
      return false;
    },
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
  });
  return { fuelGrades: data || [], isLoading, error };
};

