import { ref, reactive, watch } from "@vue/composition-api";
import { Args, ProductData } from "../types/rpsync";

const args = reactive<Args>({
  curPage: 1,
  perPage: 20,
  filters: {
    numref: "",
    title: "",
    department: "",
    brand: "",
    season: "",
    product_id: "",
  },
  sorting: {
    orderby: "numref",
    order: "ASC",
  },
});

const results = reactive({
  products: [] as ProductData[],
  total: 0,
});

const isLoading = ref<boolean>(false);

const fetch = async () => {
  try {
    isLoading.value = true;
    const response = JSON.parse(
      await $.ajax({
        url: rpsyncOptions.ajaxUrl,
        method: "POST",
        data: { operation: "fetch", args },
      }),
    );
    results.products = response.products;
    results.total = response.total;
  } catch (error) {
    console.error(error);
  } finally {
    isLoading.value = false;
  }
};

watch(args, () => fetch());

const create = async (numref: string) => {
  isLoading.value = true;
  const response = JSON.parse(
    await $.ajax({
      url: rpsyncOptions.ajaxUrl,
      method: "POST",
      data: { operation: "create", numref },
    }),
  );
  isLoading.value = false;
  if (response.error) {
    throw new Error(response.error);
  }
};

const update = async (numref: string) => {
  isLoading.value = true;
  const response = JSON.parse(
    await $.ajax({
      url: rpsyncOptions.ajaxUrl,
      method: "POST",
      data: { operation: "update", numref },
    }),
  );
  isLoading.value = false;
  if (response.error) {
    throw new Error(response.error);
  }
};

const destroy = async (numref: string) => {
  isLoading.value = true;
  const response = JSON.parse(
    await $.ajax({
      url: rpsyncOptions.ajaxUrl,
      method: "POST",
      data: { operation: "destroy", numref },
    }),
  );
  isLoading.value = false;
  if (response.error) {
    throw new Error(response.error);
  }
};

export function useRPSync() {
  return { args, results, isLoading, filterOptions: rpsyncOptions.filterOptions, fetch, create, update, destroy };
}
