"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExternalApiKeyRotationService = void 0;
const ROTATION_COUNTER_KEY = 'external-api-key:rotation:counter';
class ExternalApiKeyRotationService {
    redis;
    logger;
    constructor(redis, logger) {
        this.redis = redis;
        this.logger = logger;
    }
    async selectApiKey(apiKeys) {
        if (apiKeys.length === 0) {
            throw new Error('No API keys available for rotation');
        }
        const index = await this.getNextIndex(apiKeys.length);
        return apiKeys[index];
    }
    async getNextIndex(keyCount) {
        try {
            const counter = await this.redis.incr(ROTATION_COUNTER_KEY);
            return (counter - 1) % keyCount;
        }
        catch (error) {
            this.logger.warn('Redis external API key rotation counter failed, falling back to random', {
                error,
            });
            return Math.floor(Math.random() * keyCount);
        }
    }
}
exports.ExternalApiKeyRotationService = ExternalApiKeyRotationService;
//# sourceMappingURL=external-api-key-rotation.service.js.map