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

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

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

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

  return useQuery<PostGetDates, BaseAxiosError>({
    queryKey: triumphsQueryKeys.getDates(),
    queryFn: async () => {
      if (!netInfo?.isInternetReachable) {
        const localData = loadData<string[] | null>('triumphs', 'dates');
        if (localData) {
          return { dates: localData, result: 'OK' } as PostGetDates;
        }
        return { dates: [], result: 'ERROR' } as PostGetDates;
      }

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