const Redis = require('ioredis');
const rateLimit = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');

const redisClient = new Redis(process.env.REDIS_URL, {
  enableOfflineQueue: false,
  retryStrategy: (times) => Math.min(times * 50, 2000)
});

const rateLimiterRedis = rateLimit({
  store: new RedisStore({
    sendCommand: (...args) => redisClient.call(...args)
  }),
  windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 15 * 60 * 1000,
  max: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS) || 100,
  message: { status: 'error', message: 'Too many requests' },
  standardHeaders: true,
  legacyHeaders: false,
  keyGenerator: (req) => req.headers['x-forwarded-for'] || req.ip,
  skip: (req) => req.path === '/health'
});

module.exports = { rateLimiterRedis, redisClient };