"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const common = require("./common.cjs");
const react = require("react");
const reactClient = require("@contember/react-client");
const useIDPStateStore = require("./useIDPStateStore.cjs");
const signInIDP = require("../../mutations/idp/signInIDP.cjs");
const useHandleIDPResponse = ({ onLogin, onError }) => {
  const idpSignIn = signInIDP.useSignInIDP();
  const setSessionToken = reactClient.useSetSessionToken();
  const hasOauthResponse = react.useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    return params.has("state") && (params.has("code") || params.has("id_token"));
  }, []);
  const [state, setState] = react.useState(() => hasOauthResponse ? { type: "processing" } : { type: "nothing" });
  const firstRenderRef = react.useRef(true);
  const setError = react.useCallback((err) => {
    setState({ type: "failed", error: err });
    onError?.(err);
  }, [onError]);
  const { get: loadIdpState } = useIDPStateStore.useIDPStateStore();
  react.useEffect(() => {
    if (!hasOauthResponse || !firstRenderRef.current) {
      return;
    }
    firstRenderRef.current = false;
    (async () => {
      const idpState = loadIdpState();
      if (!idpState) {
        setError("INVALID_LOCAL_STATE");
        return;
      }
      const response = await idpSignIn({
        url: window.location.href,
        redirectUrl: common.getBaseHref(),
        session: idpState.sessionData,
        identityProvider: idpState.provider,
        expiration: 3600 * 24 * 14
      });
      if (!response.ok) {
        setError(response.error.code);
      } else {
        setSessionToken(response.result.token);
        setState({ type: "succeed" });
        onLogin?.();
      }
    })();
  }, [idpSignIn, onLogin, setSessionToken, hasOauthResponse, onError, setError, loadIdpState]);
  return state;
};
exports.useHandleIDPResponse = useHandleIDPResponse;
//# sourceMappingURL=useHandleIDPResponse.cjs.map
