"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxRuntime = require("react/jsx-runtime");
const designSystem = require("@strapi/design-system");
const helperPlugin = require("@strapi/helper-plugin");
const Icons = require("@strapi/icons");
const isEqual = require("lodash/isEqual");
const reactIntl = require("react-intl");
const reactRedux = require("react-redux");
const useAdminRoles = require("./useAdminRoles-68d5d608.js");
const AuthenticatedApp = require("./AuthenticatedApp-bb793364.js");
const React = require("react");
const produce = require("immer");
const omit = require("lodash/omit");
const pick = require("lodash/pick");
const set = require("lodash/set");
const yup = require("yup");
const formatAPIErrors = require("./formatAPIErrors-b599cf27.js");
require("react-query");
require("semver/functions/lt");
require("semver/functions/valid");
require("./index-3649838b.js");
require("react-dom/client");
require("invariant");
require("lodash/isFunction");
require("lodash/merge");
require("react-helmet");
require("react-router-dom");
require("@radix-ui/react-context");
require("@strapi/design-system/v2");
require("formik");
require("lodash/camelCase");
require("styled-components");
require("lodash/defaultsDeep");
require("qs");
require("lodash/get");
require("@reduxjs/toolkit");
require("react-dnd");
require("react-dnd-html5-backend");
require("lodash/cloneDeep");
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 isEqual__default = /* @__PURE__ */ _interopDefault(isEqual);
const React__namespace = /* @__PURE__ */ _interopNamespace(React);
const produce__default = /* @__PURE__ */ _interopDefault(produce);
const omit__default = /* @__PURE__ */ _interopDefault(omit);
const pick__default = /* @__PURE__ */ _interopDefault(pick);
const set__default = /* @__PURE__ */ _interopDefault(set);
const yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
const initialState = {
  fieldsToPick: [],
  formErrors: {},
  initialData: {},
  isLoading: true,
  modifiedData: {},
  showHeaderButtonLoader: false,
  showHeaderLoader: true
};
const reducer = (state, action) => produce__default.default(state, (draftState) => {
  switch (action.type) {
    case "GET_DATA_SUCCEEDED": {
      draftState.isLoading = false;
      draftState.showHeaderLoader = false;
      draftState.initialData = pick__default.default(action.data, state.fieldsToPick);
      draftState.modifiedData = pick__default.default(action.data, state.fieldsToPick);
      break;
    }
    case "ON_CANCEL": {
      draftState.modifiedData = state.initialData;
      draftState.formErrors = {};
      break;
    }
    case "ON_CHANGE": {
      if (action.keys.includes("username") && !action.value) {
        set__default.default(draftState.modifiedData, action.keys.split("."), null);
      } else {
        set__default.default(draftState.modifiedData, action.keys.split("."), action.value);
      }
      break;
    }
    case "ON_SUBMIT": {
      draftState.showHeaderButtonLoader = true;
      break;
    }
    case "ON_SUBMIT_SUCCEEDED": {
      draftState.initialData = pick__default.default(action.data, state.fieldsToPick);
      draftState.modifiedData = pick__default.default(action.data, state.fieldsToPick);
      draftState.showHeaderButtonLoader = false;
      break;
    }
    case "SET_ERRORS": {
      draftState.formErrors = action.errors;
      draftState.showHeaderButtonLoader = false;
      break;
    }
    default:
      return draftState;
  }
});
const checkFormValidity = async (data, schema2) => {
  let errors = null;
  try {
    await schema2.validate(data, { abortEarly: false });
  } catch (err) {
    if (err instanceof yup.ValidationError) {
      errors = helperPlugin.getYupInnerErrors(err);
    }
  }
  return errors;
};
const useSettingsForm = (schema2, cbSuccess, fieldsToPick) => {
  const [
    { formErrors, initialData, isLoading, modifiedData, showHeaderButtonLoader, showHeaderLoader },
    dispatch
  ] = React__namespace.useReducer(reducer, { ...initialState, fieldsToPick });
  const toggleNotification = helperPlugin.useNotification();
  const { lockApp, unlockApp } = helperPlugin.useOverlayBlocker();
  const { get, put } = helperPlugin.useFetchClient();
  React__namespace.useEffect(() => {
    const getData = async () => {
      try {
        const {
          data: { data }
        } = await get("/admin/providers/options");
        dispatch({
          type: "GET_DATA_SUCCEEDED",
          data,
          fieldsToPick
        });
      } catch (err) {
        toggleNotification({
          type: "warning",
          message: { id: "notification.error" }
        });
      }
    };
    getData();
  }, []);
  const handleCancel = () => {
    dispatch({
      type: "ON_CANCEL"
    });
  };
  const handleChange = ({
    target: { name, value }
  }) => {
    dispatch({
      type: "ON_CHANGE",
      keys: name,
      value
    });
  };
  const setField = (fieldName, value) => {
    dispatch({
      type: "ON_CHANGE",
      keys: fieldName,
      value
    });
  };
  const handleSubmit = async (e) => {
    e.preventDefault();
    const errors = await checkFormValidity(modifiedData, schema2);
    dispatch({
      type: "SET_ERRORS",
      errors: errors || {}
    });
    if (!errors) {
      try {
        lockApp();
        dispatch({
          type: "ON_SUBMIT"
        });
        const cleanedData = omit__default.default(modifiedData, ["confirmPassword", "registrationToken"]);
        if (cleanedData.roles) {
          cleanedData.roles = cleanedData.roles.map((role) => role.id);
        }
        if (cleanedData.ssoLockedRoles) {
          cleanedData.ssoLockedRoles = [...new Set(cleanedData.ssoLockedRoles)];
        }
        const {
          data: { data }
        } = await put("/admin/providers/options", cleanedData);
        cbSuccess(data);
        dispatch({
          type: "ON_SUBMIT_SUCCEEDED",
          data
        });
        toggleNotification({
          type: "success",
          message: { id: "notification.success.saved" }
        });
      } catch (err) {
        const data = err?.response?.payload ?? { data: {} };
        if (!!data?.data && typeof data.data === "string") {
          toggleNotification({
            type: "warning",
            message: data.data
          });
        } else {
          toggleNotification({
            type: "warning",
            message: data.message
          });
        }
        const apiErrors = formatAPIErrors.formatAPIErrors(data);
        dispatch({
          type: "SET_ERRORS",
          errors: apiErrors
        });
      } finally {
        unlockApp();
      }
    }
  };
  return [
    { formErrors, initialData, isLoading, modifiedData, showHeaderButtonLoader, showHeaderLoader },
    dispatch,
    { handleCancel, handleChange, handleSubmit, setField }
  ];
};
const schema = yup__namespace.object().shape({
  autoRegister: yup__namespace.bool().required(helperPlugin.translatedErrors.required),
  defaultRole: yup__namespace.mixed().when("autoRegister", (value, initSchema) => {
    return value ? initSchema.required(helperPlugin.translatedErrors.required) : initSchema.nullable();
  }),
  ssoLockedRoles: yup__namespace.array().nullable().of(
    yup__namespace.mixed().when("ssoLockedRoles", (value, initSchema) => {
      return value ? initSchema.required(helperPlugin.translatedErrors.required) : initSchema.nullable();
    })
  )
});
const SingleSignOn = () => {
  helperPlugin.useFocusWhenNavigate();
  const { formatMessage } = reactIntl.useIntl();
  const permissions = reactRedux.useSelector(AuthenticatedApp.selectAdminPermissions);
  const {
    isLoading: isLoadingPermissions,
    allowedActions: { canUpdate, canReadRoles }
  } = helperPlugin.useRBAC({
    ...permissions.settings.sso,
    readRoles: permissions.settings.roles.read
  });
  const [
    { formErrors, initialData, isLoading: isLoadingForm, modifiedData, showHeaderButtonLoader },
    ,
    { handleChange, handleSubmit }
  ] = useSettingsForm(schema, () => {
  }, ["autoRegister", "defaultRole", "ssoLockedRoles"]);
  const { roles, isLoading: isLoadingRoles } = useAdminRoles.useAdminRoles(void 0, {
    enabled: canReadRoles
  });
  const isLoading = isLoadingPermissions || isLoadingRoles || isLoadingForm;
  return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Layout, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.SettingsPageTitle, { name: "SSO" }),
    /* @__PURE__ */ jsxRuntime.jsx(designSystem.Main, { tabIndex: -1, children: /* @__PURE__ */ jsxRuntime.jsxs("form", { onSubmit: handleSubmit, children: [
      /* @__PURE__ */ jsxRuntime.jsx(
        designSystem.HeaderLayout,
        {
          primaryAction: /* @__PURE__ */ jsxRuntime.jsx(
            designSystem.Button,
            {
              "data-testid": "save-button",
              disabled: isEqual__default.default(initialData, modifiedData),
              loading: showHeaderButtonLoader,
              startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Check, {}),
              type: "submit",
              size: "L",
              children: formatMessage({
                id: "global.save",
                defaultMessage: "Save"
              })
            }
          ),
          title: formatMessage({ id: "Settings.sso.title", defaultMessage: "Single Sign-On" }),
          subtitle: formatMessage({
            id: "Settings.sso.description",
            defaultMessage: "Configure the settings for the Single Sign-On feature."
          })
        }
      ),
      /* @__PURE__ */ jsxRuntime.jsx(designSystem.ContentLayout, { children: isLoading ? /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.LoadingIndicatorPage, {}) : /* @__PURE__ */ jsxRuntime.jsxs(
        designSystem.Flex,
        {
          direction: "column",
          alignItems: "stretch",
          gap: 4,
          background: "neutral0",
          padding: 6,
          shadow: "filterShadow",
          hasRadius: true,
          children: [
            /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "delta", as: "h2", children: formatMessage({
              id: "global.settings",
              defaultMessage: "Settings"
            }) }),
            /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Grid, { gap: 4, children: [
              /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 6, m: 6, s: 12, children: /* @__PURE__ */ jsxRuntime.jsx(
                designSystem.ToggleInput,
                {
                  "aria-label": "autoRegister",
                  "data-testid": "autoRegister",
                  disabled: !canUpdate,
                  checked: modifiedData.autoRegister,
                  hint: formatMessage({
                    id: "Settings.sso.form.registration.description",
                    defaultMessage: "Create new user on SSO login if no account exists"
                  }),
                  label: formatMessage({
                    id: "Settings.sso.form.registration.label",
                    defaultMessage: "Auto-registration"
                  }),
                  name: "autoRegister",
                  offLabel: formatMessage({
                    id: "app.components.ToggleCheckbox.off-label",
                    defaultMessage: "Off"
                  }),
                  onLabel: formatMessage({
                    id: "app.components.ToggleCheckbox.on-label",
                    defaultMessage: "On"
                  }),
                  onChange: (e) => {
                    handleChange({
                      target: { name: "autoRegister", value: e.target.checked }
                    });
                  }
                }
              ) }),
              /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 6, m: 6, s: 12, children: /* @__PURE__ */ jsxRuntime.jsx(
                designSystem.Select,
                {
                  disabled: !canUpdate,
                  hint: formatMessage({
                    id: "Settings.sso.form.defaultRole.description",
                    defaultMessage: "It will attach the new authenticated user to the selected role"
                  }),
                  error: formErrors.defaultRole ? formatMessage({
                    id: formErrors.defaultRole.id,
                    defaultMessage: formErrors.defaultRole.id
                  }) : "",
                  label: formatMessage({
                    id: "Settings.sso.form.defaultRole.label",
                    defaultMessage: "Default role"
                  }),
                  name: "defaultRole",
                  onChange: (value) => {
                    handleChange({ target: { name: "defaultRole", value } });
                  },
                  placeholder: formatMessage({
                    id: "components.InputSelect.option.placeholder",
                    defaultMessage: "Choose here"
                  }),
                  value: modifiedData.defaultRole,
                  children: roles.map(({ id, name }) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.Option, { value: id.toString(), children: name }, id))
                }
              ) }),
              /* @__PURE__ */ jsxRuntime.jsx(designSystem.GridItem, { col: 6, m: 6, s: 12, children: /* @__PURE__ */ jsxRuntime.jsx(
                designSystem.MultiSelect,
                {
                  disabled: !canUpdate,
                  hint: formatMessage({
                    id: "Settings.sso.form.localAuthenticationLock.description",
                    defaultMessage: "Select the roles for which you want to disable the local authentication"
                  }),
                  error: formErrors.ssoLockedRoles ? formatMessage({
                    id: formErrors.ssoLockedRoles.id,
                    defaultMessage: formErrors.ssoLockedRoles.id
                  }) : "",
                  label: formatMessage({
                    id: "Settings.sso.form.localAuthenticationLock.label",
                    defaultMessage: "Local authentication lock-out"
                  }),
                  name: "ssoLockedRoles",
                  onChange: (value) => {
                    handleChange({ target: { name: "ssoLockedRoles", value } });
                  },
                  placeholder: formatMessage({
                    id: "components.InputSelect.option.placeholder",
                    defaultMessage: "Choose here"
                  }),
                  onClear: () => {
                    handleChange({ target: { name: "ssoLockedRoles" } });
                  },
                  value: modifiedData.ssoLockedRoles || [],
                  withTags: true,
                  children: roles.map(({ id, name }) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.MultiSelectOption, { value: id.toString(), children: name }, id))
                }
              ) })
            ] })
          ]
        }
      ) })
    ] }) })
  ] });
};
const ProtectedSSO = () => {
  const permissions = reactRedux.useSelector(AuthenticatedApp.selectAdminPermissions);
  return /* @__PURE__ */ jsxRuntime.jsx(helperPlugin.CheckPagePermissions, { permissions: permissions.settings.sso.main, children: /* @__PURE__ */ jsxRuntime.jsx(SingleSignOn, {}) });
};
exports.SingleSignOn = SingleSignOn;
exports.default = ProtectedSSO;
//# sourceMappingURL=index-5dcdb3cd.js.map
