package requestip

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

func TestFromRequestPrefersXRealIP(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/", nil)
	req.RemoteAddr = "10.0.0.10:5555"
	req.Header.Set("X-Forwarded-For", "198.51.100.1")
	req.Header.Set("X-Real-IP", "203.0.113.10")

	if got := FromRequest(req); got != "203.0.113.10" {
		t.Fatalf("FromRequest() = %q, want %q", got, "203.0.113.10")
	}
}

func TestFromRequestUsesXForwardedForFirstValue(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/", nil)
	req.RemoteAddr = "10.0.0.10:5555"
	req.Header.Set("X-Forwarded-For", "198.51.100.7, 10.1.1.2")

	if got := FromRequest(req); got != "198.51.100.7" {
		t.Fatalf("FromRequest() = %q, want %q", got, "198.51.100.7")
	}
}

func TestFromRequestFallsBackToRemoteAddr(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/", nil)
	req.RemoteAddr = "192.0.2.5:1234"

	if got := FromRequest(req); got != "192.0.2.5" {
		t.Fatalf("FromRequest() = %q, want %q", got, "192.0.2.5")
	}
}
