import { useQuery } from "react-query";
import axios from "axios";
import { SearchMessageRes } from "../../types/ResType";
import Cookies from "js-cookie";
import { useAppSelector } from "../../utils/hooks";

export const useSearchMessages = (searchText: string) => {
  const token = Cookies.get("whoxa_web_token");
  const currentConversationData = useAppSelector(
    (state) => state.CurrentConversation,
  );
  return useQuery<SearchMessageRes, Error>(
    ["chat/search-message", searchText],
    async () => {
      const response = await axios.post<SearchMessageRes>(
        `${import.meta.env.VITE_API_URL}chat/search-message`,
        { search_text: searchText, chat_id: currentConversationData.chat_id },
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );

      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
      enabled: currentConversationData.chat_id > 0 && searchText.length > 0,
    },
  );
};
