/**
 * Custom Throttle Guard with User-based Rate Limiting
 */

import { Injectable, ExecutionContext } from '@nestjs/common';
import { ThrottlerGuard, ThrottlerException } from '@nestjs/throttler';

@Injectable()
export class CustomThrottlerGuard extends ThrottlerGuard {
  /**
   * Generate key for rate limiting based on user ID or IP
   */
  protected async getTracker(req: Record<string, any>): Promise<string> {
    // If user is authenticated, use user ID
    if (req.user && req.user.sub) {
      return `user-${req.user.sub}`;
    }

    // Otherwise, use IP address
    return req.ip || req.connection.remoteAddress || 'unknown';
  }

  /**
   * Custom error message (override for new API)
   */
  protected async throwThrottlingException(_context: ExecutionContext): Promise<void> {
    throw new ThrottlerException('Too many requests. Please try again later.');
  }
}
