import pinia from "@/plugins/store.js";
import { errorAlert } from "@/components/Mudur-Ui-Kit/alert.js";
import { storeToRefs } from "pinia";
import { useUiStore } from "@/stores/UiStore";

const request = (method, action, contex) => {
  const data = contex?.data;
  const onValidationError = contex?.onValidationError;
  const beforeSend = contex?.beforeSend;
  const success = contex?.success;
  const prefix = window.gcargo.prefix;
  //const nonce = window.gcargo.nonce;
  const ajaxurl = window.gcargo.ajaxurl;
  const url = `${ajaxurl}&action=${prefix}_${action}`;
  const { loading } = storeToRefs(useUiStore(pinia));

  return window.jQuery.ajax({
    url: url,
    type: method,
    dataType: "json",
    contentType: "application/json",
    accept: "application/json",
    data: data ? JSON.stringify(data) : false,
    beforeSend: beforeSend
      ? beforeSend()
      : () => {
          loading.value = true;
        },
    success: success
      ? success()
      : () => {
          loading.value = false;
        },
    error: (e) => {
      loading.value = false;
      if (e.status === 422 && onValidationError) {
        onValidationError(e.responseJSON);
        return;
      }
      if (e.statusText !== "abort") {
        errorAlert({ message: e.responseJSON?.error_message || e.statusText || "An error occurred" });
      }
    },
  });
};

export default {
  get(action, data) {
    return request("GET", action, data);
  },
  post(action, contex) {
    return request("POST", action, contex);
  },
  delete(action, data) {
    return request("DELETE", action, data);
  },
  put(action, data) {
    return request("PUT", action, data);
  },
  patch(action, data) {
    return request("PATCH", action, data);
  },
};
