// Rate Limiting Middleware

import { Request, Response, NextFunction } from 'express';
import rateLimit from 'express-rate-limit';
import { RATE_LIMITS } from '@/shared/constants';
import { AuthenticatedRequest } from './auth.middleware';

/**
 * Create rate limiter based on tier
 */
export function createRateLimiter(tier: 'TIER_1' | 'TIER_2' | 'PRIVATE_BANK') {
  const config = RATE_LIMITS[
    tier === 'TIER_1' ? 'SOVEREIGN_TIER_1' :
    tier === 'TIER_2' ? 'SOVEREIGN_TIER_2' :
    'PRIVATE_BANK'
  ];

  return rateLimit({
    windowMs: config.windowMs,
    max: config.max,
    message: {
      success: false,
      error: {
        code: 'RATE_LIMIT_EXCEEDED',
        message: `Rate limit exceeded. Maximum ${config.max} requests per ${config.windowMs / 1000} seconds.`,
      },
      timestamp: new Date(),
    },
    standardHeaders: true,
    legacyHeaders: false,
  });
}

/**
 * Dynamic rate limiter based on user role
 */
export function dynamicRateLimitMiddleware(
  req: AuthenticatedRequest,
  res: Response,
  next: NextFunction
): void {
  // Determine tier based on API role
  let tier: 'TIER_1' | 'TIER_2' | 'PRIVATE_BANK' = 'PRIVATE_BANK';
  
  if (req.apiRole === 'sovereign_master' || req.apiRole === 'treasury') {
    tier = 'TIER_1';
  } else if (req.apiRole === 'settlement' || req.apiRole === 'api') {
    tier = 'TIER_2';
  }

  const limiter = createRateLimiter(tier);
  limiter(req, res, next);
}

