// Simple in-memory rate limiter.
// Note: resets on server restart and does not share state across multiple processes.
// Suitable for MVP; replace with Redis for production scale-out.

interface RateLimitConfig {
  windowMs: number
  max: number
}

const CONFIGS: Record<string, RateLimitConfig> = {
  login: { windowMs: 60_000, max: 10 },        // 10 attempts per minute
  register: { windowMs: 3_600_000, max: 5 },   // 5 attempts per hour
  'pair-start': { windowMs: 60_000, max: 10 }, // 10 QR-pairings per minute (M10)
}

const DEFAULT_CONFIG: RateLimitConfig = { windowMs: 60_000, max: 10 }

const store = new Map<string, { count: number; resetAt: number }>()

export function checkRateLimit(key: string): boolean {
  const prefix = key.split(':')[0]
  const config = CONFIGS[prefix] ?? DEFAULT_CONFIG
  const now = Date.now()
  const entry = store.get(key)

  if (!entry || now > entry.resetAt) {
    store.set(key, { count: 1, resetAt: now + config.windowMs })
    return true
  }

  if (entry.count >= config.max) {
    return false
  }

  entry.count++
  return true
}
