import { computed, ref, watch } from "vue";
import { useAlert } from "./alert.js";
import { useApiModelOperation } from "./apiModelOperation.js";
export function useApiModelItem(props) {
  const alert = useAlert();
  const ops = computed(() => useApiModelOperation(props.modelName));
  const modelBy = ref();
  const item = ref();
  const isLoading = ref(false);
  const fields = computed(() => {
    return props.fields || [];
  });
  const canCreate = computed(() => true);
  const canUpdate = computed(() => true);
  const canDelete = computed(() => true);
  const computedModelBy = computed(() => {
    return Object.assign({}, props.modelBy, modelBy.value);
  });
  function reload() {
    isLoading.value = true;
    item.value = void 0;
    return ops.value.read(fields.value, computedModelBy.value).then((result) => {
      if (Array.isArray(result)) {
        alert?.addAlert({ alertType: "error", message: "Return result is not single item" });
      } else {
        item.value = result;
      }
    }).catch((error) => {
      alert?.addAlert({ alertType: "error", message: error?.message ?? error });
    }).finally(() => {
      isLoading.value = false;
    });
  }
  function createItem(createItem2, callback) {
    isLoading.value = true;
    return ops.value.create(createItem2, fields.value).then((result) => {
      item.value = result;
    }).catch((error) => {
      alert?.addAlert({ alertType: "error", message: error?.message ?? error });
      reload();
    }).finally(() => {
      isLoading.value = false;
      if (callback) callback.done();
    });
  }
  function updateItem(updateItem2, callback) {
    isLoading.value = true;
    return ops.value.update(updateItem2, fields.value).then((result) => {
      item.value = result;
    }).catch((error) => {
      alert?.addAlert({ alertType: "error", message: error?.message ?? error });
      reload();
    }).finally(() => {
      isLoading.value = false;
      if (callback) callback.done();
    });
  }
  function deleteItem(deleteItem2, callback) {
    isLoading.value = true;
    return ops.value.delete(deleteItem2, fields.value).catch((error) => {
      alert?.addAlert({ alertType: "error", message: error?.message ?? error });
    }).finally(() => {
      isLoading.value = false;
      reload();
      if (callback) callback.done();
    });
  }
  watch([() => props.modelName, () => props.modelKey, computedModelBy], () => {
    reload();
  }, { immediate: true, deep: true });
  return {
    modelBy,
    item,
    isLoading,
    fields,
    canCreate,
    canUpdate,
    canDelete,
    createItem,
    updateItem,
    deleteItem,
    reload
  };
}
