package api

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

func TestResolveRealIP(t *testing.T) {
	tests := []struct {
		name   string
		header string // 配置的真实IP请求头
		reqHdr map[string]string
		remote string
		want   string
	}{
		{name: "未配置头取 RemoteAddr", header: "", reqHdr: map[string]string{"X-Forwarded-For": "1.2.3.4"}, remote: "127.0.0.1:5000", want: "127.0.0.1"},
		{name: "XFF 单值", header: "X-Forwarded-For", reqHdr: map[string]string{"X-Forwarded-For": "203.0.113.7"}, remote: "127.0.0.1:5000", want: "203.0.113.7"},
		{name: "XFF 链取尾防伪造", header: "X-Forwarded-For", reqHdr: map[string]string{"X-Forwarded-For": "6.6.6.6, 203.0.113.7"}, remote: "127.0.0.1:5000", want: "203.0.113.7"},
		{name: "XFF 缺失回退 RemoteAddr", header: "X-Forwarded-For", reqHdr: nil, remote: "192.0.2.9:1234", want: "192.0.2.9"},
		{name: "X-Real-IP 单值直取", header: "X-Real-IP", reqHdr: map[string]string{"X-Real-IP": "203.0.113.8"}, remote: "127.0.0.1:5000", want: "203.0.113.8"},
		{name: "CF-Connecting-IP", header: "CF-Connecting-IP", reqHdr: map[string]string{"CF-Connecting-IP": "203.0.113.9", "X-Forwarded-For": "6.6.6.6"}, remote: "127.0.0.1:5000", want: "203.0.113.9"},
		{name: "RemoteAddr 无端口原样返回", header: "", reqHdr: nil, remote: "unix", want: "unix"},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			r := httptest.NewRequest("GET", "/", nil)
			r.RemoteAddr = tt.remote
			for k, v := range tt.reqHdr {
				r.Header.Set(k, v)
			}
			if got := resolveRealIP(r, tt.header); got != tt.want {
				t.Errorf("resolveRealIP = %q, want %q", got, tt.want)
			}
		})
	}
}
