import { isRateLimited } from '../rate-limit'

beforeEach(() => {
  jest.useFakeTimers()
  jest.resetModules()
})

afterEach(() => {
  jest.useRealTimers()
})

describe('isRateLimited', () => {
  it('allows requests under the limit', () => {
    const ip = '1.2.3.4'
    for (let i = 0; i < 5; i++) {
      expect(isRateLimited(ip)).toBe(false)
    }
  })

  it('blocks the 6th request within the window', () => {
    const ip = '10.0.0.1'
    for (let i = 0; i < 5; i++) isRateLimited(ip)
    expect(isRateLimited(ip)).toBe(true)
  })

  it('resets after the window expires', () => {
    const ip = '10.0.0.2'
    for (let i = 0; i < 5; i++) isRateLimited(ip)
    expect(isRateLimited(ip)).toBe(true)
    jest.advanceTimersByTime(3_600_001)
    expect(isRateLimited(ip)).toBe(false)
  })

  it('tracks different IPs independently', () => {
    const ipA = '192.168.1.1'
    const ipB = '192.168.1.2'
    for (let i = 0; i < 5; i++) isRateLimited(ipA)
    expect(isRateLimited(ipA)).toBe(true)
    expect(isRateLimited(ipB)).toBe(false)
  })
})
