import { useCallback, createElement, Fragment } from "react";
import { usePersist } from "@contember/binding";
import { useShowToast } from "@contember/ui";
import { persistFeedbackDictionary } from "./persistFeedbackDictionary.js";
import { useAccessorErrorFormatter } from "../bindingFacade/errors/useAccessorErrors.js";
import { useMessageFormatter } from "../../i18n/useMessageFormatter.js";
const usePersistWithFeedback = ({
  successMessage,
  successDuration,
  errorMessage,
  errorDuration,
  afterPersistErrorMessage,
  afterPersistErrorDuration,
  ...persistOptions
} = {}) => {
  const persistAll = usePersist();
  const showToast = useShowToast();
  const formatMessage = useMessageFormatter(persistFeedbackDictionary);
  const errorFormatter = useAccessorErrorFormatter();
  return useCallback(() => {
    return persistAll(persistOptions).then((result) => {
      console.debug("persist success", result);
      showToast({
        type: "success",
        message: formatMessage(successMessage, "persistFeedback.successMessage"),
        dismiss: successDuration ?? true
      });
      if (result.type === "justSuccess" && result.afterPersistError) {
        showToast({
          type: "error",
          message: formatMessage(afterPersistErrorMessage, "persistFeedback.afterPersistErrorMessage"),
          dismiss: afterPersistErrorDuration ?? true
        });
      }
      return result;
    }).catch((result) => {
      console.debug("persist error", result);
      if (result.type === "invalidInput" && result.errors.length) {
        showToast({
          type: "error",
          message: /* @__PURE__ */ createElement(Fragment, null, formatMessage(errorMessage, "persistFeedback.errorMessage"), /* @__PURE__ */ createElement("ul", null, errorFormatter(result.errors).map((it, i) => /* @__PURE__ */ createElement("li", {
            key: i
          }, it.message)))),
          dismiss: errorDuration ?? true
        });
      } else {
        showToast({
          type: "error",
          message: formatMessage(errorMessage, "persistFeedback.errorMessage"),
          dismiss: errorDuration ?? true
        });
      }
      return Promise.reject(result);
    });
  }, [persistAll, persistOptions, showToast, formatMessage, successMessage, successDuration, afterPersistErrorMessage, afterPersistErrorDuration, errorFormatter, errorMessage, errorDuration]);
};
export { usePersistWithFeedback };
//# sourceMappingURL=usePersistWithFeedback.js.map
