package middleware

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

	"github.com/gin-gonic/gin"
)

func TestClientIP_IgnoresXFFWithoutTrustedProxy(t *testing.T) {
	gin.SetMode(gin.TestMode)
	ConfigureTrustedProxies(nil)

	w := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(w)
	c.Request = httptest.NewRequest("GET", "/", nil)
	c.Request.RemoteAddr = "203.0.113.10:12345"
	c.Request.Header.Set("X-Forwarded-For", "1.2.3.4")

	if got := ClientIP(c); got != "203.0.113.10" {
		t.Fatalf("got %s want direct remote", got)
	}
}

func TestClientIP_UsesXFFFromTrustedProxy(t *testing.T) {
	gin.SetMode(gin.TestMode)
	ConfigureTrustedProxies([]string{"127.0.0.1"})

	w := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(w)
	c.Request = httptest.NewRequest("GET", "/", nil)
	c.Request.RemoteAddr = "127.0.0.1:12345"
	c.Request.Header.Set("X-Forwarded-For", "1.2.3.4")

	if got := ClientIP(c); got != "1.2.3.4" {
		t.Fatalf("got %s want forwarded client", got)
	}
}
