package httpmiddleware

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

	"github.com/stretchr/testify/require"
)

func TestClientIPFallsBackToRemoteAddrWhenProxyIsUntrusted(t *testing.T) {
	t.Setenv("TRUST_PROXY_IPS", "")
	t.Setenv("TRUST_PROXY_CIDRS", "")

	req := httptest.NewRequest(http.MethodGet, "/", nil)
	req.RemoteAddr = "10.0.0.10:8443"
	req.Header.Set("X-Forwarded-For", "203.0.113.9, 10.0.0.10")

	require.Equal(t, "10.0.0.10", ClientIP(req))
}

func TestClientIPUsesForwardedHeadersFromTrustedProxy(t *testing.T) {
	t.Setenv("TRUST_PROXY_IPS", "")
	t.Setenv("TRUST_PROXY_CIDRS", "10.0.0.0/8")

	req := httptest.NewRequest(http.MethodGet, "/", nil)
	req.RemoteAddr = "10.0.0.10:8443"
	req.Header.Set("X-Forwarded-For", "203.0.113.9, 10.0.0.10")

	require.Equal(t, "203.0.113.9", ClientIP(req))
}
