import { useQuery } from "react-query";
import axios from "axios";
import Cookies from "js-cookie";
import { updateContactListRes } from "../Slices/ContactListSlice";
import { useAppDispatch } from "../../utils/hooks";
import { ContactListRes } from "../../types/ResType";

export const useContactList = () => {
  const token = Cookies.get("whoxa_web_token");
  const dispatch = useAppDispatch();
  return useQuery<ContactListRes, Error>(
    ["contacts/get-contacts"],
    async () => {
      const response = await axios.get<ContactListRes>(
        `${import.meta.env.VITE_API_URL}contacts/get-contacts`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );

      dispatch(updateContactListRes(response.data));

      return response.data;
    },
    {
      // Set cache time to prevent re-fetching on route changes
      staleTime: Infinity, // Data will never be considered stale
      cacheTime: Infinity, // Data will never be removed from cache
    },
  );
};
