"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GetAdminJwt = void 0;
const AppError_js_1 = require("../../shared/errors/AppError.js");
class GetAdminJwt {
    authRepository;
    credentialStore;
    refreshPromise;
    constructor(authRepository, credentialStore) {
        this.authRepository = authRepository;
        this.credentialStore = credentialStore;
    }
    async execute(forceRefresh = false) {
        const session = await this.credentialStore.load();
        if (!session?.credentials) {
            throw new AppError_js_1.ConfigurationError("Admin credentials are unavailable. Complete the Quant Whisper admin bootstrap first.");
        }
        if (!forceRefresh && session.jwt && !this.isExpired(session.jwtExpiresAt)) {
            return session.jwt;
        }
        // Deduplicate concurrent refresh attempts so only one login request is in flight.
        if (this.refreshPromise) {
            return this.refreshPromise;
        }
        this.refreshPromise = this.refresh(session).finally(() => {
            this.refreshPromise = undefined;
        });
        return this.refreshPromise;
    }
    async refresh(session) {
        if (!session.credentials) {
            throw new AppError_js_1.ConfigurationError("Admin credentials are unavailable. Complete the Quant Whisper admin bootstrap first.");
        }
        const login = await this.authRepository.loginAdmin(session.credentials);
        await this.credentialStore.save({
            ...session,
            jwt: login.token,
            jwtExpiresAt: login.expiresAt
        });
        return login.token;
    }
    isExpired(expiresAt) {
        if (!expiresAt)
            return false;
        // Refresh 60 seconds before expiry to avoid using a token that is about to expire.
        return new Date(expiresAt).getTime() - 60_000 <= Date.now();
    }
}
exports.GetAdminJwt = GetAdminJwt;
