import { getBaseHref } from "./common.js";
import { useCallback } from "react";
import { useIDPStateStore } from "./useIDPStateStore.js";
import { useInitSignInIDP } from "../../mutations/idp/initSignInIDP.js";
import { useSaveBacklink } from "../person/useRedirectToBacklink.js";
const useInitIDPRedirect = ({ onError }) => {
  const initRequest = useInitSignInIDP();
  const saveBacklink = useSaveBacklink();
  const { set: saveIdpState } = useIDPStateStore();
  return useCallback(async ({ provider }) => {
    const fail = (error = "Failed to initiate login.") => {
      onError?.(error);
      return { ok: false, error };
    };
    try {
      const response = await initRequest({
        redirectUrl: getBaseHref(),
        identityProvider: provider
      });
      if (!response.ok) {
        console.error(response.error);
        return fail();
      } else {
        saveIdpState({ provider, sessionData: response.result.sessionData });
        saveBacklink();
        window.location.href = response.result.authUrl;
        return { ok: true };
      }
    } catch (e) {
      console.error(e);
      return fail();
    }
  }, [initRequest, onError, saveBacklink, saveIdpState]);
};
export {
  useInitIDPRedirect
};
//# sourceMappingURL=useInitIDPRedirect.js.map
