package auth

import (
	"net/http/httptest"
	"testing"
	"time"
)

func TestRateLimiterAllow(t *testing.T) {
	rl := NewRateLimiter(3, time.Hour)
	for i := 0; i < 3; i++ {
		if !rl.Allow("k") {
			t.Fatalf("Allow %d unexpectedly returned false", i)
		}
	}
	if rl.Allow("k") {
		t.Error("4th Allow should have been denied")
	}
}

func TestRateLimiterPerKey(t *testing.T) {
	rl := NewRateLimiter(1, time.Hour)
	if !rl.Allow("a") {
		t.Error("first Allow(a) should pass")
	}
	if !rl.Allow("b") {
		t.Error("first Allow(b) should pass")
	}
	if rl.Allow("a") {
		t.Error("second Allow(a) should fail")
	}
}

func TestRateLimiterRefill(t *testing.T) {
	rl := NewRateLimiter(1, 50*time.Millisecond)
	if !rl.Allow("k") {
		t.Fatal("first should pass")
	}
	if rl.Allow("k") {
		t.Fatal("second should fail before refill")
	}
	time.Sleep(80 * time.Millisecond)
	if !rl.Allow("k") {
		t.Error("after refill window, should pass again")
	}
}

func TestKeyForRoute(t *testing.T) {
	r := httptest.NewRequest("POST", "/", nil)
	r.RemoteAddr = "10.0.0.1:54321"
	k := KeyForRoute("login", r)
	want := "login:10.0.0.1"
	if k != want {
		t.Errorf("got %q, want %q", k, want)
	}
}
