import type { RequestHandler } from 'express'

/** Fixed-window per-subject limiter. In-memory is enough for a single instance. */
export function rateLimit(perMinute: number): RequestHandler {
  const windows = new Map<string, { start: number; count: number }>()
  setInterval(() => {
    const cutoff = Date.now() - 60_000
    for (const [k, w] of windows) if (w.start < cutoff) windows.delete(k)
  }, 60_000).unref()

  return (req, res, next) => {
    const key = String(req.auth?.extra?.subject ?? req.ip)
    const now = Date.now()
    const w = windows.get(key)
    if (!w || now - w.start >= 60_000) {
      windows.set(key, { start: now, count: 1 })
      return next()
    }
    if (++w.count > perMinute) {
      res.set('Retry-After', String(Math.ceil((w.start + 60_000 - now) / 1000)))
      return res.status(429).json({ jsonrpc: '2.0', error: { code: -32000, message: 'Rate limit exceeded' }, id: null })
    }
    next()
  }
}
