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

import { QueryKeys } from "../constants/query-keys";
import { AddressesService } from "../services/api";
import { countriesStore } from "../stores/countriesStore";

export function useCountries() {
  //
  const { countries, setCountries, setLoading } = countriesStore();

  const { data: countriesData, refetch: getCountries } = useQuery({
    queryKey: [QueryKeys.users.GET_COUNTRIES],
    queryFn: AddressesService.addressesControllerGetCountries,
    enabled: !countries,
  });

  useEffect(() => {
    setCountries(countriesData);
    setLoading(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [countriesData, setCountries]);

  return {
    getCountries,
  };
}
