"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveHostedDemoSessionAuthWithRefresh = void 0;
const accessTokenRefresh_1 = require("./accessTokenRefresh");
const logger_1 = require("../utils/logger");
const log = (0, logger_1.createLogger)('HostedDemoSessionAuthRefresh');
/**
 * Loads hosted-demo session auth and refreshes the access token when it is near expiry.
 * After a failed refresh, re-reads from the session store so a concurrent successful refresh
 * is not ignored.
 */
const resolveHostedDemoSessionAuthWithRefresh = async (params) => {
    const { demoAuthSessionService, sessionId, res, getProxyUrl, refreshAccessTokenViaProxyFn = accessTokenRefresh_1.refreshAccessTokenViaProxy, } = params;
    let auth = demoAuthSessionService.getAuthForSessionId(sessionId);
    if (auth?.token &&
        auth.refreshToken &&
        (0, accessTokenRefresh_1.shouldProactivelyRefreshAccessToken)(auth.token)) {
        const refreshTokenForRequest = auth.refreshToken;
        const refreshed = await (0, accessTokenRefresh_1.runHostedDemoTokenRefreshSingleFlight)(sessionId, () => refreshAccessTokenViaProxyFn({
            refreshToken: refreshTokenForRequest,
            proxyUrl: getProxyUrl(),
        }));
        if (refreshed) {
            demoAuthSessionService.storeAuthForSessionId(sessionId, res, {
                token: refreshed.token,
                email: auth.email,
                refreshToken: refreshed.refreshToken ?? refreshTokenForRequest,
            });
            auth = demoAuthSessionService.getAuthForSessionId(sessionId);
        }
        else {
            log.warn('Hosted demo access token refresh failed; continuing with stored token');
            auth = demoAuthSessionService.getAuthForSessionId(sessionId);
        }
    }
    return auth;
};
exports.resolveHostedDemoSessionAuthWithRefresh = resolveHostedDemoSessionAuthWithRefresh;
//# sourceMappingURL=hostedDemoSessionAuthRefresh.js.map