"use strict";
/**
 * Shared Authentication Utilities
 *
 * Common functions for OAuth token handling across quota fetchers.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.isTokenExpired = exports.getTokenExpiryTimestamp = exports.sanitizeEmail = void 0;
/**
 * Sanitize email to match CLIProxyAPI auth file naming convention.
 * Replaces @ and . with underscores for filesystem compatibility.
 */
function sanitizeEmail(email) {
    return email.replace(/@/g, '_').replace(/\./g, '_');
}
exports.sanitizeEmail = sanitizeEmail;
/**
 * Check if token is expired based on the expired timestamp.
 * Returns false if timestamp is missing or invalid (fail-open for quota display).
 */
function getTokenExpiryTimestamp(expiredValue) {
    if (expiredValue === undefined || expiredValue === null || expiredValue === '') {
        return null;
    }
    const normalizeNumericTimestamp = (value) => {
        if (!Number.isFinite(value) || value <= 0) {
            return null;
        }
        // Support Unix seconds from older token stores while preserving millisecond timestamps.
        return value < 1000000000000 ? value * 1000 : value;
    };
    try {
        if (typeof expiredValue === 'number') {
            return normalizeNumericTimestamp(expiredValue);
        }
        const trimmed = expiredValue.trim();
        if (!trimmed) {
            return null;
        }
        if (/^\d+$/.test(trimmed)) {
            const numericTimestamp = Number(trimmed);
            return normalizeNumericTimestamp(numericTimestamp);
        }
        const expiredDate = new Date(trimmed);
        const expiredAt = expiredDate.getTime();
        return Number.isNaN(expiredAt) ? null : expiredAt;
    }
    catch {
        return null;
    }
}
exports.getTokenExpiryTimestamp = getTokenExpiryTimestamp;
function isTokenExpired(expiredValue) {
    const expiredAt = getTokenExpiryTimestamp(expiredValue);
    return expiredAt !== null ? expiredAt < Date.now() : false;
}
exports.isTokenExpired = isTokenExpired;
//# sourceMappingURL=auth-utils.js.map