import { Redis } from 'ioredis';
import { IExternalApiKeyRotationService } from '../../application/ports/external-api-key-rotation.service';
import { ILogger } from '../../application/ports/logger';

const ROTATION_COUNTER_KEY = 'external-api-key:rotation:counter';

export class ExternalApiKeyRotationService implements IExternalApiKeyRotationService {
  constructor(
    private readonly redis: Redis,
    private readonly logger: ILogger,
  ) {}

  async selectApiKey(apiKeys: string[]): Promise<string> {
    if (apiKeys.length === 0) {
      throw new Error('No API keys available for rotation');
    }

    const index = await this.getNextIndex(apiKeys.length);
    return apiKeys[index];
  }

  private async getNextIndex(keyCount: number): Promise<number> {
    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);
    }
  }
}
