import { useQuery } from '@tanstack/react-query';

import { seriesQueryKeys } from '../series-query-keys';
import { seriesApi, type PostGetSeriesRanking, type RankingData } from '../series-api';

import type { BaseAxiosError } from '../../../../types';
import { useConnection } from 'src/contexts/ConnectionContext';
import { loadData } from 'src/storage';

export const useGetSeriesRanking = (
  id: number,
  page: number,
  page_size: number,
  enabled: boolean
) => {
  const netInfo = useConnection();

  return useQuery<PostGetSeriesRanking, BaseAxiosError>({
    queryKey: seriesQueryKeys.getSeriesRanking(id, page, page_size),
    queryFn: async () => {
      if (!netInfo?.isInternetReachable) {
        const localData = loadData<RankingData>('series', `${id}`);
        if (localData) {
          return { data: localData, result: 'OK' } as PostGetSeriesRanking;
        }
        return { data: {}, result: 'ERROR' } as PostGetSeriesRanking;
      }

      const response = await seriesApi.getSeriesRanking(id, page, page_size);
      return response.data;
    },
    enabled
  });
};
