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

interface AuthenticatedRequest extends Request {
  user?: { sub?: string; role?: string };
}

/**
 * Throttler guard for the `feature-listing` endpoint.
 *
 * Extends the default ThrottlerGuard so rate limits are enforced via the
 * globally-configured Redis-backed storage (see AppModule ThrottlerModule
 * wiring). The tracker splits traffic per authenticated user when a JWT
 * payload is present, otherwise falls back to the real client IP behind
 * the reverse proxy. This produces independent per-user and per-IP buckets
 * as required by TEC-2930.
 */
@Injectable()
export class FeatureListingThrottlerGuard extends ThrottlerGuard {
  protected override getTracker(req: AuthenticatedRequest): Promise<string> {
    const userId = req.user?.sub;
    if (userId) {
      return Promise.resolve(`user:${userId}`);
    }

    const forwarded = req.headers['x-forwarded-for'];
    const ip =
      typeof forwarded === 'string'
        ? (forwarded.split(',')[0]?.trim() ?? req.ip ?? '127.0.0.1')
        : (req.ip ?? '127.0.0.1');

    return Promise.resolve(`ip:${ip}`);
  }
}
