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

import { triumphsQueryKeys } from '../triumphs-query-keys';
import { triumphsApi, type PostGetData, type TriumphsData } from '../triumphs-api';

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

export const useGetTriumphsData = (date: string, enabled: boolean) => {
  const netInfo = useConnection();

  return useQuery<PostGetData, BaseAxiosError>({
    queryKey: triumphsQueryKeys.getData(date),
    queryFn: async () => {
      if (!netInfo?.isInternetReachable) {
        const localData = loadData<TriumphsData[]>('triumphs', `data_${date}`);
        if (localData) {
          return { triumphs: localData } as PostGetData;
        }
        return { triumphs: [], result: 'ERROR' } as PostGetData;
      }

      const response = await triumphsApi.getData(date);
      return response.data;
    },
    enabled
  });
};
