/**
 * middleware/rateLimit.js
 * Login brute-force protection (5 attempts then 15min lockout)
 * and a generic API limiter.
 *
 * `scanLimiter` is also applied to /scan/* AND /cases/:id/discover
 * (see app.js). The deep discovery endpoint is the most expensive
 * thing on the system — limit it harder than scans.
 */

'use strict';

const rateLimit = require('express-rate-limit');

const loginMax = parseInt(process.env.LOGIN_MAX_ATTEMPTS, 10) || 5;
const lockoutMin = parseInt(process.env.LOGIN_LOCKOUT_MINUTES, 10) || 15;

const loginLimiter = rateLimit({
  windowMs: lockoutMin * 60 * 1000,
  max: loginMax,
  standardHeaders: true,
  legacyHeaders: false,
  message: { error: 'TOO_MANY_ATTEMPTS', message: `Too many login attempts. Try again in ${lockoutMin} minutes.` },
  // Identify by IP + email so one IP can't lock all users
  keyGenerator: (req) => `${req.ip}:${(req.body && req.body.email || '').toLowerCase()}`,
});

const apiLimiter = rateLimit({
  windowMs: 60 * 1000,
  max: 120,
  standardHeaders: true,
  legacyHeaders: false,
  message: { error: 'RATE_LIMIT', message: 'Slow down.' },
});

const scanLimiter = rateLimit({
  windowMs: 60 * 1000,
  max: 10,
  standardHeaders: true,
  legacyHeaders: false,
  message: { error: 'RATE_LIMIT', message: 'Too many scans. Wait a minute.' },
});

// 2FA: tighter limiter for the 6-digit TOTP brute force window.
// 5 attempts per session, 20 per IP per minute.
const twofaLimiter = rateLimit({
  windowMs: 60 * 1000,
  max: 20,
  standardHeaders: true,
  legacyHeaders: false,
  message: { error: 'RATE_LIMIT', message: 'Too many 2FA attempts. Slow down.' },
});

module.exports = loginLimiter;
module.exports.api = apiLimiter;
module.exports.scan = scanLimiter;
module.exports.twofa = twofaLimiter;
