package connectsrv

import (
	"net/http"
	"testing"
)

// TestPeerIP covers the client-IP extraction the chat-moderation IP and the per-IP rate
// limiter both rely on: the first X-Forwarded-For hop (the real client, once Caddy is
// configured to trust its upstream), falling back to the connection peer.
func TestPeerIP(t *testing.T) {
	tests := []struct {
		name string
		addr string
		xff  string
		want string
	}{
		{"xff single", "10.0.0.1:5000", "203.0.113.7", "203.0.113.7"},
		{"xff client then proxies", "10.0.0.1:5000", "203.0.113.7, 172.18.0.3", "203.0.113.7"},
		{"xff trims spaces", "10.0.0.1:5000", "  203.0.113.9 , 10.0.0.2", "203.0.113.9"},
		{"no xff uses peer host", "203.0.113.5:42000", "", "203.0.113.5"},
		{"no xff no port", "203.0.113.6", "", "203.0.113.6"},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			h := http.Header{}
			if tc.xff != "" {
				h.Set("X-Forwarded-For", tc.xff)
			}
			if got := peerIP(tc.addr, h); got != tc.want {
				t.Errorf("peerIP(%q, xff=%q) = %q, want %q", tc.addr, tc.xff, got, tc.want)
			}
		})
	}
}
