package resolver_test

import (
	"ekdns/platform"
	"ekdns/resolver"
	"reflect"
	"testing"
)

func TestBuildResolverPool(t *testing.T) {
	tests := []struct {
		name     string
		mode     resolver.ServerMode
		info     platform.NetworkInfo
		expected []string
	}{
		{
			name: "default mode with local resolvers prepended",
			mode: resolver.ServerMode{Mode: "default"},
			info: platform.NetworkInfo{DNSServers: []string{"10.0.0.1", "10.0.0.2"}},
			expected: []string{
				"10.0.0.1", "10.0.0.2",
				"1.1.1.1", "8.8.8.8", "1.0.0.1", "8.8.4.4", "9.9.9.9", "208.67.222.222",
			},
		},
		{
			name: "default mode deduplicates bootstrap servers already in local list",
			mode: resolver.ServerMode{Mode: "default"},
			info: platform.NetworkInfo{DNSServers: []string{"8.8.8.8", "10.0.0.1"}},
			// 8.8.8.8 is already seen from local list, so it is skipped when appending bootstraps
			expected: []string{
				"8.8.8.8", "10.0.0.1",
				"1.1.1.1", "1.0.0.1", "8.8.4.4", "9.9.9.9", "208.67.222.222",
			},
		},
		{
			name:     "default mode with no local resolvers uses only bootstrap",
			mode:     resolver.ServerMode{Mode: "default"},
			info:     platform.NetworkInfo{},
			expected: resolver.BootstrapResolvers,
		},
		{
			name:     "local mode returns only local DNS servers",
			mode:     resolver.ServerMode{Mode: "local"},
			info:     platform.NetworkInfo{DNSServers: []string{"10.0.0.1"}},
			expected: []string{"10.0.0.1"},
		},
		{
			name:     "local mode empty DNS servers returns nil",
			mode:     resolver.ServerMode{Mode: "local"},
			info:     platform.NetworkInfo{},
			expected: nil,
		},
		{
			name:     "gateway mode returns only the gateway IP",
			mode:     resolver.ServerMode{Mode: "gateway"},
			info:     platform.NetworkInfo{Gateway: "192.168.1.1"},
			expected: []string{"192.168.1.1"},
		},
		{
			name:     "explicit mode returns only the explicit address",
			mode:     resolver.ServerMode{Mode: "explicit", ExplicitAddr: "10.0.0.53:5353"},
			info:     platform.NetworkInfo{},
			expected: []string{"10.0.0.53:5353"},
		},
		{
			name:     "unknown mode returns nil",
			mode:     resolver.ServerMode{Mode: "bogus"},
			info:     platform.NetworkInfo{},
			expected: nil,
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			got := resolver.BuildResolverPool(tc.mode, tc.info)
			if !reflect.DeepEqual(got, tc.expected) {
				t.Errorf("BuildResolverPool(%+v, ...) =\n  got  %v\n  want %v", tc.mode, got, tc.expected)
			}
		})
	}
}
