import { Injectable } from '@nestjs/common';
import { ThrottlerGuard } from '@nestjs/throttler';
import { type Request } from 'express';

/**
 * Extends ThrottlerGuard to extract real client IP behind reverse proxies
 * (e.g., nginx, CloudFlare, AWS ALB) using X-Forwarded-For header.
 */
@Injectable()
export class ThrottlerBehindProxyGuard extends ThrottlerGuard {
  protected override getTracker(req: Request): Promise<string> {
    const forwarded = req.headers['x-forwarded-for'];
    const ip =
      typeof forwarded === 'string' ? (forwarded.split(',')[0]?.trim() ?? '127.0.0.1') : req.ip;
    return Promise.resolve(ip ?? '127.0.0.1');
  }
}
