package serverimp

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

func TestEffectiveProviderConfig(t *testing.T) {
	primary := gatewayProviderConfig{
		BaseURL:             "https://aurora.local",
		StrictOperationMode: true,
	}
	legacy := gatewayProviderConfig{
		BaseURL:             "https://legacy.local",
		StrictOperationMode: false,
	}

	got := effectiveProviderConfig(primary, legacy)
	if got.BaseURL != primary.BaseURL {
		t.Fatalf("expected primary provider config to be selected, got %q", got.BaseURL)
	}
	if !got.StrictOperationMode {
		t.Fatalf("expected strict operation mode from primary config")
	}
}

func TestEffectiveProviderConfig_FallsBackToLegacy(t *testing.T) {
	primary := gatewayProviderConfig{}
	legacy := gatewayProviderConfig{
		BaseURL:             "https://legacy.local",
		StrictOperationMode: true,
	}

	got := effectiveProviderConfig(primary, legacy)
	if got.BaseURL != legacy.BaseURL {
		t.Fatalf("expected legacy provider config to be selected, got %q", got.BaseURL)
	}
	if !got.StrictOperationMode {
		t.Fatalf("expected strict operation mode from legacy config")
	}
}

func TestClientIPFromRequest(t *testing.T) {
	req := &http.Request{
		Header:     http.Header{"X-Forwarded-For": []string{"1.2.3.4, 5.6.7.8"}},
		RemoteAddr: "9.8.7.6:1234",
	}
	ip := clientIPFromRequest(req)
	if ip == nil || ip.String() != "1.2.3.4" {
		t.Fatalf("expected forwarded ip, got %v", ip)
	}

	req = &http.Request{RemoteAddr: "9.8.7.6:1234"}
	ip = clientIPFromRequest(req)
	if ip == nil || ip.String() != "9.8.7.6" {
		t.Fatalf("expected remote addr ip, got %v", ip)
	}

	req = &http.Request{RemoteAddr: "invalid"}
	ip = clientIPFromRequest(req)
	if ip != nil {
		t.Fatalf("expected nil ip, got %v", ip)
	}
}

func TestClientAllowed(t *testing.T) {
	_, cidr, err := net.ParseCIDR("10.0.0.0/8")
	if err != nil {
		t.Fatalf("failed to parse cidr: %v", err)
	}

	allowedReq := &http.Request{RemoteAddr: "10.1.2.3:1234"}
	if !clientAllowed(allowedReq, []*net.IPNet{cidr}) {
		t.Fatalf("expected allowed request")
	}

	deniedReq := &http.Request{RemoteAddr: "8.8.8.8:1234"}
	if clientAllowed(deniedReq, []*net.IPNet{cidr}) {
		t.Fatalf("expected denied request")
	}

	openReq := &http.Request{RemoteAddr: "8.8.8.8:1234"}
	if !clientAllowed(openReq, nil) {
		t.Fatalf("expected allow when no cidrs are configured")
	}
}
