package identity

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

func TestClientIP(t *testing.T) {
	cases := []struct {
		name       string
		remoteAddr string
		xfwd       string
		want       string
	}{
		{"xfwd first value", "10.0.0.1:52341", "203.0.113.9, 10.0.0.2", "203.0.113.9"},
		{"xfwd single", "10.0.0.1:52341", "198.51.100.7", "198.51.100.7"},
		{"xfwd with spaces", "10.0.0.1:52341", " 192.0.2.5 ", "192.0.2.5"},
		{"no xfwd falls back to remote", "203.0.113.9:8080", "", "203.0.113.9"},
		{"no xfwd and no port", "[2001:db8::1]:443", "", "2001:db8::1"},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			req := httptest.NewRequest(http.MethodPost, "/", nil)
			req.RemoteAddr = tc.remoteAddr
			if tc.xfwd != "" {
				req.Header.Set("X-Forwarded-For", tc.xfwd)
			}
			if got := ClientIP(req); got != tc.want {
				t.Fatalf("ClientIP() = %q, want %q", got, tc.want)
			}
		})
	}
}
