import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import rateLimit from 'express-rate-limit';
import { ApiKeyRepository } from 'modules/feature/api-key/repositories/api-key.repository';

@Injectable()
export class ApiKeyRateLimiterMiddleware implements NestMiddleware {
  private readonly logger = new Logger(ApiKeyRateLimiterMiddleware.name);
  constructor(private apiKeyRepository: ApiKeyRepository) {}

  use(req: Request, res: Response, next: NextFunction) {
    const apiKey = req.headers['x-api-key'] as string;

    if (!apiKey) {
      return next();
    }

    const apiKeyLimiter = rateLimit({
      windowMs: 15 * 60 * 1000, // 15 minutes
      max: async (_req, _res) => {
        try {
          // Fetch API key details and get custom limit
          const keyDetails = await this.apiKeyRepository.findByKey(apiKey);
          return keyDetails?.rateLimit || 100; // Default to 100 if no specific limit
        } catch (error) {
          this.logger.error('Error fetching API key details', error);
          return 10; // Very low limit if key validation fails
        }
      },
      keyGenerator: () => apiKey,
      standardHeaders: true,
      legacyHeaders: false,
      message: {
        statusCode: 429,
        error: 'Too Many Requests',
        message: 'API key rate limit exceeded. Please try again later.',
      },
    });

    apiKeyLimiter(req, res, next);
  }
}
