package rest

import (
	"testing"
	"time"
)

func TestLoginRateLimiterBlocksAfterConfiguredFailures(t *testing.T) {
	now := time.Date(2026, 5, 14, 12, 0, 0, 0, time.UTC)
	limiter := newLoginRateLimiter(time.Minute, 2)
	limiter.now = func() time.Time { return now }

	key := "user|127.0.0.1"
	if !limiter.Allow(key) {
		t.Fatal("expected first attempt to be allowed")
	}
	limiter.RecordFailure(key)
	if !limiter.Allow(key) {
		t.Fatal("expected second attempt to be allowed")
	}
	limiter.RecordFailure(key)
	if limiter.Allow(key) {
		t.Fatal("expected third attempt inside the window to be blocked")
	}

	now = now.Add(time.Minute + time.Second)
	if !limiter.Allow(key) {
		t.Fatal("expected attempts to be allowed after the window expires")
	}
}

func TestLoginRateLimiterResetClearsFailures(t *testing.T) {
	limiter := newLoginRateLimiter(time.Minute, 1)
	key := "user|127.0.0.1"

	limiter.RecordFailure(key)
	if limiter.Allow(key) {
		t.Fatal("expected key to be blocked after one failure")
	}
	limiter.Reset(key)
	if !limiter.Allow(key) {
		t.Fatal("expected reset key to be allowed")
	}
}
