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

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

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

export const useGetSeriesGroupsRanking = (enabled: boolean) => {
  const netInfo = useConnection();

  return useQuery<PostGetSeriesGroupsRanking, BaseAxiosError>({
    queryKey: seriesQueryKeys.getSeriesGroupsRanking(),
    queryFn: async () => {
      if (!netInfo?.isInternetReachable) {
        const localData = loadData<GroupsData[]>('series', `groups`);
        if (localData) {
          return { data: localData } as PostGetSeriesGroupsRanking;
        }
        return { data: [], result: 'ERROR' } as PostGetSeriesGroupsRanking;
      }

      const response = await seriesApi.getSeriesGroupsRanking();
      return response.data;
    },
    enabled
  });
};
