var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { jsx as _jsx } from "react/jsx-runtime";
/* eslint-disable react-hooks/exhaustive-deps */
import { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router';
import DefaultFallback from '../../components/fallback/default';
import { useRouterContext } from '../../router/context';
import Center from '../../shared/center/center';
import { requestSessionToken, verifySessionToken } from '../auth';
/**
 * The Login component requests a new server-managed session cookie and then redirects.
 */
function DefaultAuthLogin() {
    var _a;
    const location = useLocation();
    const navigate = useNavigate();
    const { defaultPath } = useRouterContext();
    const queryParams = new URLSearchParams(location.search);
    const previousLocation = (_a = queryParams.get('referrer')) !== null && _a !== void 0 ? _a : defaultPath;
    function getNewToken() {
        return __awaiter(this, void 0, void 0, function* () {
            const sessionCreated = yield requestSessionToken({});
            // in default auth this always succeeds
            if (sessionCreated) {
                navigate(decodeURIComponent(previousLocation));
            }
        });
    }
    useEffect(() => {
        // If we landed on this page with a valid session already, redirect.
        // Otherwise, request a new session token.
        verifySessionToken().then((verificationResult) => {
            if (verificationResult === 'verified') {
                navigate(decodeURIComponent(previousLocation), { replace: true });
            }
            else if (verificationResult === 'login_required') {
                getNewToken();
            }
        });
    }, []);
    return (_jsx(Center, { children: _jsx(DefaultFallback, {}) }));
}
export default DefaultAuthLogin;
//# sourceMappingURL=default-auth-login.js.map