import {useMutation} from "@vue/apollo-composable";
import {ref} from "vue";
import {ElNotification} from "element-plus";
import {useI18n} from "vue-i18n";
import {SEARCH} from "@/graphql/mutations/search.js";

export function useSearch() {
  const {t} = useI18n();

  const { mutate: searchMutation } = useMutation(SEARCH);

  const loading = ref(false);
  const searchResults = ref(null);

  async function search(
      query
  ) {
    loading.value = true;
    searchResults.value = null;

    try {
      const response = await searchMutation({
        query
      });

      if (response.data?.search) {
        searchResults.value = response.data.search.results;
        return response.data.search;
      }
    } catch (error) {
      console.error("useSearch error:", error);

      const errorMessage = error.graphQLErrors?.[0]?.message ||
          error.message ||
          t('popup.errors.defaultError');

      ElNotification({
        title: t('popup.errors.main'),
        message: errorMessage,
        type: 'error'
      });
    } finally {
      loading.value = false;
    }
  }

  return {
    search,
    loading,
    searchResults
  };
}