import { usePersist } from "@contember/binding";
import { useShowToast } from "@contember/ui";
import { useCallback } from "react";
import { persistFeedbackDictionary } from "./persistFeedbackDictionary.js";
import { jsxDEV, Fragment } from "react/jsx-dev-runtime";
import { useAccessorErrorFormatter } from "../bindingFacade/errors/useAccessorErrors.js";
import { useMessageFormatter } from "../../i18n/useMessageFormatter.js";
var _jsxFileName = "/__w/interface/interface/packages/admin/src/components/ui/usePersistWithFeedback.tsx";
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__ */ jsxDEV(Fragment, {
            children: [formatMessage(errorMessage, "persistFeedback.errorMessage"), /* @__PURE__ */ jsxDEV("ul", {
              children: errorFormatter(result.errors).map((it, i) => /* @__PURE__ */ jsxDEV("li", {
                children: it.message
              }, i, false, {
                fileName: _jsxFileName,
                lineNumber: 64,
                columnNumber: 56
              }, void 0))
            }, void 0, false, {
              fileName: _jsxFileName,
              lineNumber: 63,
              columnNumber: 9
            }, void 0)]
          }, void 0, true),
          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
