import { describe, expect, it } from 'vitest'
import { LOGIN_LIMITS, clientIp, rateLimit, rateLimitReset, rateLimitStatus } from '@/lib/security/rate-limit'

/** Sign-in brute-force protection and the API limiter (2026-09-22). */
describe('rate limiter', () => {
  it('allows up to the limit, then blocks with a retry-after', () => {
    const key = `t:${Math.random()}`
    for (let i = 0; i < 3; i++) expect(rateLimit(key, 3, 60_000).allowed).toBe(true)
    const blocked = rateLimit(key, 3, 60_000)
    expect(blocked.allowed).toBe(false)
    expect(blocked.retryAfterSeconds).toBeGreaterThan(0)
    expect(rateLimitStatus(key, 3, 60_000).allowed).toBe(false)
  })
  it('a successful sign-in clears the counter', () => {
    const key = `t:${Math.random()}`
    for (let i = 0; i < 3; i++) rateLimit(key, 3, 60_000)
    rateLimitReset(key)
    expect(rateLimit(key, 3, 60_000).allowed).toBe(true)
  })
  it('login policy: 10 per username, 30 per IP, 15 minutes', () => {
    expect(LOGIN_LIMITS).toEqual({ perUser: 10, perIp: 30, windowMs: 900_000 })
  })
  it('client ip prefers the first forwarded hop', () => {
    expect(clientIp(new Headers({ 'x-forwarded-for': '203.0.113.9, 10.0.0.1' }))).toBe('203.0.113.9')
    expect(clientIp(new Headers())).toBe('unknown')
  })
})
