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

import { rankingQueryKeys } from '../ranking-query-keys';
import { type PostGetMaster, rankingApi } from '../ranking-api';

import type { BaseAxiosError } from '../../../../types';
import { storage, StoreType } from 'src/storage';

export const useGetMaster = (
  country: string,
  age: number,
  ranking: string,
  rows: number,
  page: number,
  enabled: boolean
) => {
  const storageKey = `masterRanking-${page}`;
  const fallbackData = storage.get(storageKey, StoreType.STRING) as string;
  const initialData = fallbackData ? (JSON.parse(fallbackData) as PostGetMaster) : undefined;

  return useQuery<PostGetMaster, BaseAxiosError>({
    queryKey: rankingQueryKeys.getMaster(country, age, ranking, rows, page),
    queryFn: async () => {
      const response = await rankingApi.getMaster(country, age, ranking, rows, page);
      const result = response.data;

      if (result && page <= 20) {
        storage.set(storageKey, JSON.stringify(result));
      }

      return result;
    },
    initialData,
    gcTime: 0,
    staleTime: 0,
    enabled
  });
};
