const windows = new Map()

const DEFAULT_MAX_ATTEMPTS = 5
const DEFAULT_WINDOW_MS = 60_000

// Per-endpoint rate limits
const LIMITS = {
  login: { maxAttempts: 5, windowMs: 60_000 },
  codeRequest: { maxAttempts: 3, windowMs: 60_000 },
  codeVerify: { maxAttempts: 5, windowMs: 60_000 },
}

setInterval(() => {
  const now = Date.now()
  for (const [ip, entry] of windows) {
    if (now - entry.start > DEFAULT_WINDOW_MS) windows.delete(ip)
  }
}, 5 * 60_000).unref()

function getKey(ip, scope) {
  return `${scope}:${ip}`
}

function checkRateLimit(ip, scope) {
  const limit = LIMITS[scope] || { maxAttempts: DEFAULT_MAX_ATTEMPTS, windowMs: DEFAULT_WINDOW_MS }
  const key = getKey(ip, scope)
  const now = Date.now()
  const entry = windows.get(key)
  if (!entry || now - entry.start > limit.windowMs) {
    windows.set(key, { start: now, count: 1 })
    return { allowed: true }
  }
  entry.count += 1
  if (entry.count > limit.maxAttempts) {
    const retryAfter = Math.ceil((entry.start + limit.windowMs - now) / 1000)
    return { allowed: false, retryAfter }
  }
  return { allowed: true }
}

export function checkLoginRateLimit(ip) {
  return checkRateLimit(ip, 'login')
}

export function checkCodeRequestRateLimit(ip) {
  return checkRateLimit(ip, 'codeRequest')
}

export function checkCodeVerifyRateLimit(ip) {
  return checkRateLimit(ip, 'codeVerify')
}
