import { verifyApi } from '@/apis';
import { VERIFY_USER_QUERY_KEY } from '@/constants';
import { useSettingStore } from '@/stores';
import { useQuery, useQueryClient } from '@tanstack/vue-query';
import { storeToRefs } from 'pinia';
import { computed, watch } from 'vue';

export const useVerifyUserQuery = () => {
  const queryClient = useQueryClient();
  const settingStore = useSettingStore();
  const { activeRequests } = storeToRefs(settingStore);

  watch(activeRequests, (active) => {
    if (!active) {
      queryClient.cancelQueries({ queryKey: [VERIFY_USER_QUERY_KEY] });
    }
  });

  return useQuery({
    queryKey: [VERIFY_USER_QUERY_KEY],
    enabled: computed(() => activeRequests.value),
    refetchInterval: 10 * 1000,
    queryFn: async ({ signal }) => {
      await verifyApi({ signal });
      return null;
    },
  });
};
