import { useCallback } from "react" import { useGetSession } from "./useGetSession" import { useSignOut } from "./useSignOut" function useEnsureNoSessionAndFetchNonce() { const { refetch: getSession } = useGetSession(undefined, { enabled: false, retry: false, }) const { signOutAsync } = useSignOut() const getAndValidateSession = useCallback(async () => { const getSessionResult = await getSession() // TODO: We should create a separate endpoint that will always return nonce if (getSessionResult.error) { throw new Error( `Sign in error: Failed to fetch the current session: ${getSessionResult.error}`, ) } if (!getSessionResult.data) { throw new Error( "Sign in error: Failed to fetch the current session; no data returned.", ) } return getSessionResult.data }, [getSession]) const ensureNoSessionAndFetchNonce = useCallback(async () => { let getSessionResult = await getAndValidateSession() if (!("nonce" in getSessionResult)) { // If there is active session we are terminating it await signOutAsync() // Because we've signed out we can assume nonce will be returned here getSessionResult = (await getAndValidateSession()) as { nonce: string } } return getSessionResult.nonce }, [getAndValidateSession, signOutAsync]) return { ensureNoSessionAndFetchNonce } } export { useEnsureNoSessionAndFetchNonce }