import { useQuery } from '@tanstack/react-query';
import { useInject } from '@/lib/di/hooks/useInject';
import { RACE_SERVICE_TOKEN } from '@/lib/di/tokens';
import { RacesViewDataBuilder } from '@/lib/builders/view-data/RacesViewDataBuilder';
import { RacesViewData } from '@/lib/view-data/RacesViewData';

export function useAllRacesPageData(initialData?: RacesViewData | null) {
  const raceService = useInject(RACE_SERVICE_TOKEN);

  return useQuery({
    queryKey: ['races', 'all'],
    queryFn: async () => {
      const result = await raceService.getAllRacesPageData();
      if (result.isErr()) {
        throw new Error(result.getError().message);
      }
      return RacesViewDataBuilder.build(result.unwrap());
    },
    initialData: initialData ?? undefined,
    staleTime: 1000 * 60 * 5,
    retry: false,
    refetchOnWindowFocus: false,
  });
}
