package service

import (
	"testing"
	"time"
)

func TestSourceIPLimitSharedAndReleased(t *testing.T) {
	m := &sourceIPLimitManager{buckets: make(map[string]*sourceIPBucket)}
	m.Configure("forward-1", 2, 10*time.Millisecond)
	a, ok := m.Acquire("forward-1", "192.0.2.1")
	if !ok {
		t.Fatal("first IP should be allowed")
	}
	b, ok := m.Acquire("forward-1", "192.0.2.1")
	if !ok {
		t.Fatal("same IP should reuse a slot")
	}
	c, ok := m.Acquire("forward-1", "192.0.2.2")
	if !ok {
		t.Fatal("second IP should be allowed")
	}
	if _, ok := m.Acquire("forward-1", "192.0.2.3"); ok {
		t.Fatal("third IP should be denied")
	}
	a.Release()
	b.Release()
	c.Release()
	time.Sleep(15 * time.Millisecond)
	if _, ok := m.Acquire("forward-1", "192.0.2.3"); !ok {
		t.Fatal("expired slots should be released")
	}
}

func TestNormalizeSourceIP(t *testing.T) {
	if got := normalizeSourceIP("[::ffff:192.0.2.10]:1234"); got != "192.0.2.10" {
		t.Fatalf("unexpected normalized IP: %s", got)
	}
}
