import { SetMetadata } from '@nestjs/common';

/**
 * Metadata key for per-endpoint rate limit configuration.
 * Read by EndpointRateLimitGuard via reflector.
 */
export const ENDPOINT_RATE_LIMIT_KEY = 'endpoint_rate_limit';

export interface EndpointRateLimitOptions {
  /**
   * Maximum number of requests allowed within the window.
   * @example 5 (for login: 5 attempts per minute)
   */
  limit: number;

  /**
   * Sliding window duration in seconds.
   * @default 60
   */
  windowSeconds?: number;

  /**
   * Key strategy for identifying the requester:
   * - `'ip'`   — key by client IP (for unauthenticated endpoints like login/register)
   * - `'user'` — key by authenticated user ID (falls back to IP if unauthenticated)
   * @default 'ip'
   */
  keyStrategy?: 'ip' | 'user';

  /**
   * Whether ADMIN users bypass this rate limit.
   * @default true
   */
  adminBypass?: boolean;
}

/**
 * Decorator to configure per-endpoint rate limiting with Redis sliding window.
 *
 * Works in conjunction with `EndpointRateLimitGuard`. Apply it to specific
 * controller methods or the entire controller class to enforce granular
 * rate limits keyed by IP or authenticated user + endpoint path.
 *
 * @example
 * // Login: 5 attempts per minute per IP
 * @EndpointRateLimit({ limit: 5, windowSeconds: 60, keyStrategy: 'ip' })
 *
 * @example
 * // Listing creation: 10 per minute per user
 * @EndpointRateLimit({ limit: 10, windowSeconds: 60, keyStrategy: 'user' })
 *
 * @example
 * // Search: 30 per minute per user, admin bypass enabled
 * @EndpointRateLimit({ limit: 30, windowSeconds: 60, keyStrategy: 'user', adminBypass: true })
 */
export const EndpointRateLimit = (options: EndpointRateLimitOptions) =>
  SetMetadata<string, EndpointRateLimitOptions>(ENDPOINT_RATE_LIMIT_KEY, options);
