"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TokenManager = void 0;
const fs_1 = __importDefault(require("fs"));
const crypto_1 = __importDefault(require("crypto"));
const path_1 = __importDefault(require("path"));
const TOKEN_FILE = path_1.default.resolve(__dirname, 'ms_token.enc');
const SECRET_KEY = crypto_1.default.createHash('sha256').update('Minecraft-Core-Master SecretKey').digest(); // 32 bytes para AES-256
const IV_LENGTH = 16; // AES CBC IV length
class TokenManager {
    token = null;
    constructor() {
        this.loadToken();
    }
    // --- Cifrar ---
    encrypt(data) {
        const iv = crypto_1.default.randomBytes(IV_LENGTH);
        const cipher = crypto_1.default.createCipheriv('aes-256-cbc', SECRET_KEY, iv);
        const encrypted = Buffer.concat([cipher.update(data, 'utf8'), cipher.final()]).toString('hex');
        return iv.toString('hex') + ':' + encrypted;
    }
    // --- Descifrar ---
    decrypt(data) {
        const [ivHex, encryptedHex] = data.split(':');
        if (!ivHex || !encryptedHex)
            throw new Error('Token corrupto o inválido');
        const iv = Buffer.from(ivHex, 'hex');
        const encrypted = Buffer.from(encryptedHex, 'hex');
        const decipher = crypto_1.default.createDecipheriv('aes-256-cbc', SECRET_KEY, iv);
        const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf8');
        return decrypted;
    }
    // --- Guardar en archivo ---
    saveToken() {
        if (!this.token)
            return;
        fs_1.default.writeFileSync(TOKEN_FILE, this.encrypt(JSON.stringify(this.token)), 'utf8');
    }
    // --- Cargar desde archivo ---
    loadToken() {
        if (!fs_1.default.existsSync(TOKEN_FILE))
            return;
        try {
            const encrypted = fs_1.default.readFileSync(TOKEN_FILE, 'utf8');
            this.token = JSON.parse(this.decrypt(encrypted));
        }
        catch (err) {
            console.error('No se pudo leer token:', err);
            this.token = null;
        }
    }
    // --- Login manual (guardar token luego de Microsoft login) ---
    login(tokenData) {
        this.token = tokenData;
        this.token.obtained_at = Math.floor(Date.now() / 1000);
        this.saveToken();
    }
    // --- Logout (eliminar token) ---
    logout() {
        this.token = null;
        if (fs_1.default.existsSync(TOKEN_FILE))
            fs_1.default.unlinkSync(TOKEN_FILE);
    }
    // --- Obtener token actual ---
    getToken() {
        if (!this.token)
            return null;
        // Verificar si expiro (10s de margen)
        const now = Math.floor(Date.now() / 1000);
        if (now > this.token.obtained_at + this.token.expires_in - 10) {
            console.warn('El token ha expirado, se debe refrescar.');
            return null;
        }
        return this.token;
    }
    // --- Actualizar token (refresh_token) ---
    refresh(newTokenData) {
        if (!this.token)
            return;
        this.token = { ...this.token, ...newTokenData, obtained_at: Math.floor(Date.now() / 1000) };
        this.saveToken();
    }
}
exports.TokenManager = TokenManager;
