"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxDevRuntime = require("react/jsx-dev-runtime");
const reactClient = require("@contember/react-client");
const ui = require("@contember/ui");
const react = require("react");
const MiscPageLayout = require("../MiscPageLayout.cjs");
const InvalidIdentityFallback = require("./InvalidIdentityFallback.cjs");
const useLogout = require("./useLogout.cjs");
const reactBinding = require("@contember/react-binding");
const IdentityEnvironmentExtension = require("./IdentityEnvironmentExtension.cjs");
const me = require("../../tenant/queries/me.cjs");
const IdentityContext = react.createContext(void 0);
const IdentityRefreshContext = react.createContext(() => {
  throw new Error("IdentityRefreshContext is not initialized");
});
const IdentityProvider = ({ children, onInvalidIdentity, allowUnauthenticated }) => {
  const sessionToken = reactClient.useSessionToken();
  const fetchMe = me.useFetchMe();
  const [identityState, setIdentityState] = react.useState(() => ({ state: sessionToken ? "loading" : "none" }));
  const logout = useLogout.useLogout();
  const clearIdentity = react.useCallback(() => setIdentityState({ state: "cleared" }), []);
  const refetch = react.useCallback(async () => {
    setIdentityState({ state: "loading" });
    try {
      const response = await fetchMe();
      const person = response.data.me.person;
      const projects = response.data.me.projects;
      const permissions = response.data.me.permissions;
      setIdentityState({
        state: "success",
        identity: {
          id: response.data.me.id,
          person: person ?? void 0,
          projects: projects.map((it) => ({
            name: it.project.name,
            slug: it.project.slug,
            roles: it.memberships.map((it2) => it2.role)
          })),
          permissions,
          email: person?.email ?? void 0,
          otpEnabled: person?.otpEnabled ?? void 0,
          personId: person?.id ?? void 0
        }
      });
    } catch (e) {
      console.error(e);
      if (typeof e === "object" && e !== null && "status" in e && e.status === 401) {
        logout({ noRedirect: true });
        clearIdentity();
        if (onInvalidIdentity) {
          onInvalidIdentity();
        } else if (window.location.pathname !== "/") {
          window.location.href = "/";
        }
      } else {
        setIdentityState({ state: "failed" });
      }
    }
  }, [clearIdentity, fetchMe, logout, onInvalidIdentity]);
  react.useEffect(
    () => {
      if (sessionToken === void 0) {
        setIdentityState({ state: "none" });
        if (!allowUnauthenticated) {
          if (onInvalidIdentity) {
            onInvalidIdentity();
          } else if (window.location.pathname !== "/") {
            window.location.href = "/";
          }
        }
        return;
      }
    },
    [sessionToken, allowUnauthenticated, onInvalidIdentity]
  );
  react.useEffect(
    () => {
      if (sessionToken !== void 0) {
        refetch();
      }
    },
    [sessionToken, refetch]
  );
  const identityContextValue = react.useMemo(
    () => identityState.state === "success" ? { clearIdentity, identity: identityState.identity } : void 0,
    [identityState, clearIdentity]
  );
  if (identityState.state === "cleared") {
    return /* @__PURE__ */ jsxDevRuntime.jsxDEV(MiscPageLayout.MiscPageLayout, { children: /* @__PURE__ */ jsxDevRuntime.jsxDEV(ui.Message, { size: "large", padding: "large", display: "block", children: "Logging out…" }, void 0, false, {
      fileName: "/__w/interface/interface/packages/admin/src/components/Identity/IdentityProvider.tsx",
      lineNumber: 149,
      columnNumber: 5
    }, void 0) }, void 0, false, {
      fileName: "/__w/interface/interface/packages/admin/src/components/Identity/IdentityProvider.tsx",
      lineNumber: 148,
      columnNumber: 4
    }, void 0);
  }
  if (identityState.state === "failed") {
    return /* @__PURE__ */ jsxDevRuntime.jsxDEV(InvalidIdentityFallback.InvalidIdentityFallback, {}, void 0, false, {
      fileName: "/__w/interface/interface/packages/admin/src/components/Identity/IdentityProvider.tsx",
      lineNumber: 155,
      columnNumber: 10
    }, void 0);
  }
  const pending = identityState.state === "loading" || !allowUnauthenticated && identityState.state === "none";
  return /* @__PURE__ */ jsxDevRuntime.jsxDEV(ui.SpinnerContainer, { enabled: pending, children: pending ? null : /* @__PURE__ */ jsxDevRuntime.jsxDEV(reactBinding.EnvironmentExtensionProvider, { extension: IdentityEnvironmentExtension.identityEnvironmentExtension, state: identityContextValue?.identity ?? null, children: /* @__PURE__ */ jsxDevRuntime.jsxDEV(IdentityContext.Provider, { value: identityContextValue, children: /* @__PURE__ */ jsxDevRuntime.jsxDEV(IdentityRefreshContext.Provider, { value: refetch, children }, void 0, false, {
    fileName: "/__w/interface/interface/packages/admin/src/components/Identity/IdentityProvider.tsx",
    lineNumber: 165,
    columnNumber: 7
  }, void 0) }, void 0, false, {
    fileName: "/__w/interface/interface/packages/admin/src/components/Identity/IdentityProvider.tsx",
    lineNumber: 164,
    columnNumber: 6
  }, void 0) }, void 0, false, {
    fileName: "/__w/interface/interface/packages/admin/src/components/Identity/IdentityProvider.tsx",
    lineNumber: 163,
    columnNumber: 5
  }, void 0) }, void 0, false, {
    fileName: "/__w/interface/interface/packages/admin/src/components/Identity/IdentityProvider.tsx",
    lineNumber: 161,
    columnNumber: 3
  }, void 0);
};
exports.IdentityContext = IdentityContext;
exports.IdentityProvider = IdentityProvider;
exports.IdentityRefreshContext = IdentityRefreshContext;
//# sourceMappingURL=IdentityProvider.cjs.map
