import { useLazyQuery } from "@vue/apollo-composable";
import { computed, ref } from "vue";
import { GET_PRODUCTS } from "@/graphql/queries/products.js";

export function useProducts() {
  const variables = ref({
    first: 12
  });

  const { result, loading, error, load } = useLazyQuery(
    GET_PRODUCTS,
    () => variables.value
  );

  const products = computed(() => result.value?.products.edges ?? []);
  const pageInfo = computed(() => result.value?.products.pageInfo ?? {});

  if (error.value) {
    console.error("useProducts error:", error.value);
  }

  const getProducts = async (params = {}) => {
    const newVariables = { ...variables.value };

    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        newVariables[key] = value;
      }
    });

    variables.value = newVariables;

    if (result.value) {
      await refetch();
    } else {
      await load();
    }
  };

  return {
    products,
    pageInfo,
    loading,
    error,
    getProducts
  };
}