/**
 * Brute-force guard for the login form: after 5 failures for an IP+username, lock for 15 minutes.
 * (Magento also locks the admin account itself after its own failure limit.)
 */
export class LoginThrottle {
  private readonly failures = new Map<string, { count: number; first: number; lockedUntil: number }>()

  constructor(
    private readonly maxFailures = 5,
    private readonly windowMs = 15 * 60_000,
  ) {
    setInterval(() => {
      const now = Date.now()
      for (const [k, v] of this.failures) if (v.lockedUntil < now && now - v.first > this.windowMs) this.failures.delete(k)
    }, 60_000).unref()
  }

  /** Seconds the key must wait, or 0. */
  blockedFor(key: string): number {
    const f = this.failures.get(key)
    return f && f.lockedUntil > Date.now() ? Math.ceil((f.lockedUntil - Date.now()) / 1000) : 0
  }

  fail(key: string) {
    const now = Date.now()
    const f = this.failures.get(key)
    if (!f || now - f.first > this.windowMs) {
      this.failures.set(key, { count: 1, first: now, lockedUntil: 0 })
      return
    }
    if (++f.count >= this.maxFailures) f.lockedUntil = now + this.windowMs
  }

  succeed(key: string) {
    this.failures.delete(key)
  }
}
