"use strict";
/**
 * @fileoverview Token Storage Adapter
 *
 * Provides the method to convert between:
 * 1. Legacy TokenStore (callback-based) to SDK-Gen TokenStorage (promise-based)
 * 2. Legacy TokenInfo structure to sdk-gen AccessToken structure
 */
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LegacyTokenStoreAdapter = void 0;
exports.convertLegacyTokenInfoToAccessToken = convertLegacyTokenInfoToAccessToken;
exports.convertAccessTokenToLegacyTokenInfo = convertAccessTokenToLegacyTokenInfo;
exports.wrapLegacyTokenStore = wrapLegacyTokenStore;
function convertLegacyTokenInfoToAccessToken(legacyTokenInfo) {
    if (!legacyTokenInfo) {
        return undefined;
    }
    // Calculate expiresIn (seconds) from TTL and acquired time
    const currentTimeMS = Date.now();
    const expiresAtMS = legacyTokenInfo.acquiredAtMS + legacyTokenInfo.accessTokenTTLMS;
    const remainingMS = expiresAtMS - currentTimeMS;
    const expiresInSeconds = Math.max(0, Math.floor(remainingMS / 1000));
    return {
        accessToken: legacyTokenInfo.accessToken,
        refreshToken: legacyTokenInfo.refreshToken,
        expiresIn: expiresInSeconds,
        tokenType: 'bearer',
    };
}
/**
 * Convert sdk-gen AccessToken to legacy TokenInfo
 *
 * @param accessToken The sdk-gen AccessToken
 * @param acquiredAtMS Optional timestamp of when token was acquired (defaults to now)
 */
function convertAccessTokenToLegacyTokenInfo(accessToken, acquiredAtMS) {
    if (!accessToken || !accessToken.accessToken) {
        return null;
    }
    const acquired = acquiredAtMS || Date.now();
    // Convert expiresIn (seconds) to accessTokenTTLMS (milliseconds)
    const ttlMS = (accessToken.expiresIn || 3600) * 1000;
    return {
        accessToken: accessToken.accessToken,
        refreshToken: accessToken.refreshToken,
        accessTokenTTLMS: ttlMS,
        acquiredAtMS: acquired,
    };
}
/**
 * Adapter class that wraps a legacy callback-based TokenStore
 * and makes it compatible with sdk-gen's promise-based TokenStorage interface
 */
class LegacyTokenStoreAdapter {
    constructor(legacyStore) {
        this.legacyStore = legacyStore;
    }
    /**
     * Store an AccessToken by converting it to legacy TokenInfo format
     */
    store(token) {
        return __awaiter(this, void 0, void 0, function* () {
            const legacyTokenInfo = convertAccessTokenToLegacyTokenInfo(token);
            if (!legacyTokenInfo) {
                throw new Error('Cannot store invalid token');
            }
            return new Promise((resolve, reject) => {
                this.legacyStore.write(legacyTokenInfo, (err) => {
                    if (err) {
                        reject(err);
                    }
                    else {
                        resolve(undefined);
                    }
                });
            });
        });
    }
    /**
     * Retrieve an AccessToken by reading legacy TokenInfo and converting it
     */
    get() {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                this.legacyStore.read((err, legacyTokenInfo) => {
                    if (err) {
                        reject(err);
                    }
                    else {
                        const accessToken = convertLegacyTokenInfoToAccessToken(legacyTokenInfo);
                        resolve(accessToken);
                    }
                });
            });
        });
    }
    /**
     * Clear the token store
     */
    clear() {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                this.legacyStore.clear((err) => {
                    if (err) {
                        reject(err);
                    }
                    else {
                        resolve(undefined);
                    }
                });
            });
        });
    }
}
exports.LegacyTokenStoreAdapter = LegacyTokenStoreAdapter;
/**
 * Convenience function to wrap a legacy TokenStore as sdk-gen TokenStorage
 */
function wrapLegacyTokenStore(legacyStore) {
    return new LegacyTokenStoreAdapter(legacyStore);
}
//# sourceMappingURL=token-storage-adapter.js.map