import { ThrottlerStorage } from '@nestjs/throttler';
import Redis from 'ioredis';

export class RedisThrottlerStorage implements ThrottlerStorage {
  private redis: Redis;

  constructor() {
    this.redis = new Redis({
      host: process.env.REDIS_HOST || 'localhost',
      port: parseInt(process.env.REDIS_PORT || '6379', 10),
      password: process.env.REDIS_PASSWORD || undefined,
      keyPrefix: 'throttle:',
    });
  }

  async increment(key: string, ttl: number, limit: number, blockDuration: number, throttlerName: string): Promise<{
    totalHits: number;
    timeToExpire: number;
    isBlocked: boolean;
    timeToBlockExpire: number;
  }> {
    const redisKey = `throttle:${throttlerName}:${key}`;
    const total = await this.redis.incr(redisKey);
    if (total === 1) {
      await this.redis.pexpire(redisKey, ttl);
    }
    const ttlRemaining = await this.redis.pttl(redisKey);
    return {
      totalHits: total,
      timeToExpire: Math.max(0, Math.ceil(ttlRemaining / 1000)),
      isBlocked: total > limit,
      timeToBlockExpire: total > limit ? Math.max(0, Math.ceil(ttlRemaining / 1000)) : 0,
    };
  }
}
