"use strict";
const jsxRuntime = require("react/jsx-runtime");
const React = require("react");
const designSystem = require("@strapi/design-system");
const helperPlugin = require("@strapi/helper-plugin");
const formik = require("formik");
const reactIntl = require("react-intl");
const reactQuery = require("react-query");
const reactRedux = require("react-redux");
const reactRouterDom = require("react-router-dom");
const AuthenticatedApp = require("./AuthenticatedApp-bb793364.js");
const formatAPIErrors = require("./formatAPIErrors-b599cf27.js");
const constants = require("./constants-da2542a3.js");
const index = require("./index-d3e1fd86.js");
const PropTypes = require("prop-types");
const Icons = require("@strapi/icons");
require("date-fns");
require("date-fns/locale");
const yup = require("yup");
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
function _interopNamespace(e) {
  if (e && e.__esModule)
    return e;
  const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
  if (e) {
    for (const k in e) {
      if (k !== "default") {
        const d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: () => e[k]
        });
      }
    }
  }
  n.default = e;
  return Object.freeze(n);
}
const PropTypes__default = /* @__PURE__ */ _interopDefault(PropTypes);
const yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
const FormTransferTokenContainer = ({
  errors,
  onChange,
  canEditInputs,
  isCreating,
  values,
  transferToken
}) => {
  const { formatMessage } = reactIntl.useIntl();
  const typeOptions = [
    {
      value: "push",
      label: {
        id: "Settings.transferTokens.types.push",
        defaultMessage: "Push"
      }
    },
    {
      value: "pull",
      label: {
        id: "Settings.transferTokens.types.pull",
        defaultMessage: "Pull"
      }
    },
    {
      value: "push-pull",
      label: {
        id: "Settings.transferTokens.types.push-pull",
        defaultMessage: "Full Access"
      }
    }
  ];
  return /* @__PURE__ */ jsxRuntime.jsx(
    designSystem.Box,
    {
      background: "neutral0",
      hasRadius: true,
      shadow: "filterShadow",
      paddingTop: 6,
      paddingBottom: 6,
      paddingLeft: 7,
      paddingRight: 7,
      children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
        /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "delta", as: "h2", children: formatMessage({
          id: "global.details",
          defaultMessage: "Details"
        }) }),
        /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Grid, { gap: 5, children: [
          /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 6, xs: 12, children: /* @__PURE__ */ jsxRuntime.jsx(
            index.TokenName,
            {
              errors,
              values,
              canEditInputs,
              onChange
            }
          ) }, "name"),
          /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 6, xs: 12, children: /* @__PURE__ */ jsxRuntime.jsx(
            index.TokenDescription,
            {
              errors,
              values,
              canEditInputs,
              onChange
            }
          ) }, "description"),
          /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 6, xs: 12, children: /* @__PURE__ */ jsxRuntime.jsx(
            index.LifeSpanInput,
            {
              isCreating,
              errors,
              values,
              onChange,
              token: transferToken
            }
          ) }, "lifespan"),
          /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 6, xs: 12, children: /* @__PURE__ */ jsxRuntime.jsx(
            index.TokenTypeSelect,
            {
              name: "permissions",
              values,
              errors,
              label: {
                id: "Settings.tokens.form.type",
                defaultMessage: "Token type"
              },
              onChange: (value) => {
                onChange({ target: { name: "permissions", value } });
              },
              options: typeOptions,
              canEditInputs
            }
          ) }, "permissions")
        ] })
      ] })
    }
  );
};
FormTransferTokenContainer.propTypes = {
  errors: PropTypes__default.default.shape({
    name: PropTypes__default.default.string,
    description: PropTypes__default.default.string,
    lifespan: PropTypes__default.default.string,
    type: PropTypes__default.default.string
  }),
  onChange: PropTypes__default.default.func.isRequired,
  canEditInputs: PropTypes__default.default.bool.isRequired,
  values: PropTypes__default.default.shape({
    name: PropTypes__default.default.string,
    description: PropTypes__default.default.string,
    lifespan: PropTypes__default.default.oneOfType([PropTypes__default.default.number, PropTypes__default.default.string]),
    type: PropTypes__default.default.string
  }).isRequired,
  isCreating: PropTypes__default.default.bool.isRequired,
  transferToken: PropTypes__default.default.shape({
    id: PropTypes__default.default.oneOfType([PropTypes__default.default.number, PropTypes__default.default.string]),
    type: PropTypes__default.default.string,
    lifespan: PropTypes__default.default.string,
    name: PropTypes__default.default.string,
    accessKey: PropTypes__default.default.string,
    permissions: PropTypes__default.default.array,
    description: PropTypes__default.default.string,
    createdAt: PropTypes__default.default.string
  })
};
FormTransferTokenContainer.defaultProps = {
  errors: {},
  transferToken: {}
};
const LoadingView = ({ transferTokenName }) => {
  const { formatMessage } = reactIntl.useIntl();
  helperPlugin.useFocusWhenNavigate();
  return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Main, { "aria-busy": "true", children: [
    /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.SettingsPageTitle, { name: "Transfer Tokens" }),
    /* @__PURE__ */ jsxRuntime.jsx(
      designSystem.HeaderLayout,
      {
        primaryAction: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { disabled: true, startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Check, {}), type: "button", size: "L", children: formatMessage({ id: "global.save", defaultMessage: "Save" }) }),
        title: transferTokenName || formatMessage({
          id: "Settings.transferTokens.createPage.title",
          defaultMessage: "Create Transfer Token"
        })
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(designSystem.ContentLayout, { children: /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.LoadingIndicatorPage, {}) })
  ] });
};
LoadingView.defaultProps = {
  transferTokenName: null
};
LoadingView.propTypes = {
  transferTokenName: PropTypes__default.default.string
};
const schema = yup__namespace.object().shape({
  name: yup__namespace.string(helperPlugin.translatedErrors.string).max(100).required(helperPlugin.translatedErrors.required),
  description: yup__namespace.string().nullable(),
  lifespan: yup__namespace.number().integer().min(0).nullable().defined(helperPlugin.translatedErrors.required),
  permissions: yup__namespace.string(helperPlugin.translatedErrors.string).required(helperPlugin.translatedErrors.required)
});
const MSG_ERROR_NAME_TAKEN = "Name already taken";
const TransferTokenCreateView = () => {
  helperPlugin.useFocusWhenNavigate();
  const { formatMessage } = reactIntl.useIntl();
  const { lockApp, unlockApp } = helperPlugin.useOverlayBlocker();
  const toggleNotification = helperPlugin.useNotification();
  const history = reactRouterDom.useHistory();
  const [transferToken, setTransferToken] = React.useState(
    history.location.state?.transferToken.accessKey ? {
      ...history.location.state.transferToken
    } : null
  );
  const { trackUsage } = helperPlugin.useTracking();
  const trackUsageRef = React.useRef(trackUsage);
  const { setCurrentStep } = helperPlugin.useGuidedTour();
  const permissions = reactRedux.useSelector(AuthenticatedApp.selectAdminPermissions);
  const {
    allowedActions: { canCreate, canUpdate, canRegenerate }
  } = helperPlugin.useRBAC(permissions.settings["transfer-tokens"]);
  const {
    params: { id }
  } = reactRouterDom.useRouteMatch("/settings/transfer-tokens/:id");
  const { get, post, put } = helperPlugin.useFetchClient();
  const isCreating = id === "create";
  const { formatAPIError } = helperPlugin.useAPIErrorHandler();
  React.useEffect(() => {
    trackUsageRef.current(isCreating ? "didAddTokenFromList" : "didEditTokenFromList", {
      tokenType: constants.TRANSFER_TOKEN_TYPE
    });
  }, [isCreating]);
  const { status } = reactQuery.useQuery(
    ["transfer-token", id],
    async () => {
      const {
        data: { data }
      } = await get(`/admin/transfer/tokens/${id}`);
      setTransferToken({
        ...data
      });
      return data;
    },
    {
      enabled: !isCreating && !transferToken,
      onError(err) {
        if (err.response.data.error.details?.code === "INVALID_TOKEN_SALT") {
          toggleNotification({
            type: "warning",
            message: {
              id: "notification.error.invalid.configuration",
              defaultMessage: "You have an invalid configuration, check your server log for more information."
            }
          });
        } else {
          toggleNotification({
            type: "warning",
            message: formatAPIError(err)
          });
        }
      }
    }
  );
  const handleSubmit = async (body, actions) => {
    trackUsageRef.current(isCreating ? "willCreateToken" : "willEditToken", {
      tokenType: constants.TRANSFER_TOKEN_TYPE
    });
    lockApp();
    const lifespanVal = body.lifespan && parseInt(body.lifespan, 10) && body.lifespan !== "0" ? parseInt(body.lifespan, 10) : null;
    const permissions2 = body.permissions.split("-");
    try {
      const {
        data: { data: response }
      } = isCreating ? await post(`/admin/transfer/tokens`, {
        ...body,
        lifespan: lifespanVal,
        permissions: permissions2
      }) : await put(`/admin/transfer/tokens/${id}`, {
        name: body.name,
        description: body.description,
        permissions: permissions2
      });
      unlockApp();
      if (isCreating) {
        history.replace(`/settings/transfer-tokens/${response.id}`, { transferToken: response });
        setCurrentStep("transferTokens.success");
      }
      setTransferToken({
        ...response
      });
      toggleNotification({
        type: "success",
        message: isCreating ? formatMessage({
          id: "notification.success.transfertokencreated",
          defaultMessage: "Transfer Token successfully created"
        }) : formatMessage({
          id: "notification.success.transfertokenedited",
          defaultMessage: "Transfer Token successfully edited"
        })
      });
      trackUsageRef.current(isCreating ? "didCreateToken" : "didEditToken", {
        type: transferToken?.permissions,
        tokenType: constants.TRANSFER_TOKEN_TYPE
      });
    } catch (err) {
      const errors = formatAPIErrors.formatAPIErrors(err.response.data);
      actions.setErrors(errors);
      if (err?.response?.data?.error?.message === MSG_ERROR_NAME_TAKEN) {
        toggleNotification({
          type: "warning",
          message: err.response.data.message || "notification.error.tokennamenotunique"
        });
      } else if (err?.response?.data?.error?.details?.code === "INVALID_TOKEN_SALT") {
        toggleNotification({
          type: "warning",
          message: {
            id: "notification.error.invalid.configuration",
            defaultMessage: "You have an invalid configuration, check your server log for more information."
          }
        });
      } else {
        toggleNotification({
          type: "warning",
          message: err?.response?.data?.message || "notification.error"
        });
      }
      unlockApp();
    }
  };
  const canEditInputs = canUpdate && !isCreating || canCreate && isCreating;
  const isLoading = !isCreating && !transferToken && status !== "success";
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntime.jsx(LoadingView, { transferTokenName: transferToken?.name });
  }
  const handleErrorRegenerate = (err) => {
    if (err?.response?.data?.error?.details?.code === "INVALID_TOKEN_SALT") {
      toggleNotification({
        type: "warning",
        message: {
          id: "notification.error.invalid.configuration",
          defaultMessage: "You have an invalid configuration, check your server log for more information."
        }
      });
    } else {
      toggleNotification({
        type: "warning",
        message: formatAPIError(err)
      });
    }
  };
  return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Main, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.SettingsPageTitle, { name: "Transfer Tokens" }),
    /* @__PURE__ */ jsxRuntime.jsx(
      formik.Formik,
      {
        validationSchema: schema,
        validateOnChange: false,
        initialValues: {
          name: transferToken?.name || "",
          description: transferToken?.description || "",
          lifespan: transferToken?.lifespan ? transferToken.lifespan.toString() : transferToken?.lifespan,
          permissions: transferToken?.permissions.join("-")
        },
        enableReinitialize: true,
        onSubmit: (body, actions) => handleSubmit(body, actions),
        children: ({ errors, handleChange, isSubmitting, values }) => {
          return /* @__PURE__ */ jsxRuntime.jsxs(helperPlugin.Form, { children: [
            /* @__PURE__ */ jsxRuntime.jsx(
              index.FormHead,
              {
                backUrl: "/settings/transfer-tokens",
                title: {
                  id: "Settings.transferTokens.createPage.title",
                  defaultMessage: "Create Transfer Token"
                },
                token: transferToken,
                setToken: setTransferToken,
                canEditInputs,
                canRegenerate,
                isSubmitting,
                regenerateUrl: "/admin/transfer/tokens/",
                onErrorRegenerate: handleErrorRegenerate
              }
            ),
            /* @__PURE__ */ jsxRuntime.jsx(designSystem.ContentLayout, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 6, children: [
              Boolean(transferToken?.name) && /* @__PURE__ */ jsxRuntime.jsx(index.TokenBox, { token: transferToken?.accessKey, tokenType: constants.TRANSFER_TOKEN_TYPE }),
              /* @__PURE__ */ jsxRuntime.jsx(
                FormTransferTokenContainer,
                {
                  errors,
                  onChange: handleChange,
                  canEditInputs,
                  isCreating,
                  values,
                  transferToken
                }
              )
            ] }) })
          ] });
        }
      }
    )
  ] });
};
exports.TransferTokenCreateView = TransferTokenCreateView;
//# sourceMappingURL=index-c4287359.js.map
