import { useState, useEffect, createElement } from "react";
import { ErrorList, ContainerSpinner } from "@contember/ui";
import { getBaseHref, IDP_SESSION_KEY, IDP_CODE } from "./common.js";
import { useSetSessionToken } from "@contember/react-client";
import { useSignInIDP } from "../../mutations/idp/signInIDP.js";
const IDPResponseHandler = ({ onLogin }) => {
  const idpSignIn = useSignInIDP();
  const [error, setError] = useState();
  const setSessionToken = useSetSessionToken();
  useEffect(() => {
    (async () => {
      const response = await idpSignIn({
        url: window.location.href,
        redirectUrl: getBaseHref(),
        session: JSON.parse(localStorage.getItem(IDP_SESSION_KEY) || "{}"),
        identityProvider: localStorage.getItem(IDP_CODE) ?? "",
        expiration: 3600 * 24 * 14
      });
      setError(void 0);
      if (!response.ok) {
        window.history.pushState({}, document.title, "/");
        switch (response.error.code) {
          case "IDP_VALIDATION_FAILED":
          case "INVALID_IDP_RESPONSE":
            return setError("Login failed");
          case "PERSON_NOT_FOUND":
            return setError("User not found");
        }
      } else {
        setSessionToken(response.result.token);
        onLogin?.();
      }
    })();
  }, [idpSignIn, setError, onLogin, setSessionToken]);
  if (error) {
    return /* @__PURE__ */ createElement(ErrorList, {
      errors: [{ message: error }]
    });
  }
  return /* @__PURE__ */ createElement(ContainerSpinner, null);
};
export { IDPResponseHandler };
//# sourceMappingURL=IDPResponseHandler.js.map
