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";
import { useCallback, useEffect, useMemo } from 'react';
import { useLocation, useNavigate } from 'react-router';
import { HTTP_METHOD } from '@darajs/ui-utils';
import { request } from '../../api/http';
import DefaultFallback from '../../components/fallback/default';
import { useRouterContext } from '../../router/context';
import Center from '../../shared/center/center';
import { handleAuthErrors, verifySessionToken } from '../auth';
/**
 * The Login component gets the username and password from the user and generates a session token.
 */
function OIDCAuthLogin() {
    const navigate = useNavigate();
    const location = useLocation();
    const { defaultPath } = useRouterContext();
    const previousLocation = useMemo(() => {
        var _a;
        const queryParams = new URLSearchParams(location.search);
        return (_a = queryParams.get('referrer')) !== null && _a !== void 0 ? _a : defaultPath;
    }, [location, defaultPath]);
    /**
     * Get new token
     */
    const getNewToken = useCallback(() => __awaiter(this, void 0, void 0, function* () {
        const res = yield request('/api/auth/session', {
            body: JSON.stringify({
                redirect_to: previousLocation,
            }),
            method: HTTP_METHOD.POST,
        });
        // check for auth errors, redirecting to /error as needed
        const loggedOut = yield handleAuthErrors(res, false);
        if (loggedOut) {
            return;
        }
        // Redirect to the SSO login page
        // The redirect_uri already contains the state parameter with the encoded redirect URL
        if (res.ok) {
            const resContent = yield res.json();
            window.location.href = resContent.redirect_uri;
        }
    }), [previousLocation]);
    useEffect(() => {
        // If we already have a valid session, redirect. Otherwise start OIDC login.
        verifySessionToken().then((verified) => {
            if (verified) {
                navigate(decodeURIComponent(previousLocation), { replace: true });
            }
            else {
                getNewToken();
            }
        });
    }, [getNewToken, navigate, previousLocation]);
    return (_jsx(Center, { children: _jsx(DefaultFallback, {}) }));
}
export default OIDCAuthLogin;
//# sourceMappingURL=oidc-login.js.map