package networking

import "testing"

func TestValidateIfaceConfig(t *testing.T) {
	tests := []struct {
		name    string
		cfg     IfaceConfig
		wantErr bool
	}{
		{"valid static", IfaceConfig{
			Method: "static", Address: "192.168.1.10", Prefix: 24, Gateway: "192.168.1.1",
			DNS: []string{"1.1.1.1", "8.8.8.8"},
		}, false},
		{"valid static no gateway", IfaceConfig{
			Method: "static", Address: "10.0.0.5", Prefix: 8,
		}, false},
		{"valid dhcp", IfaceConfig{Method: "dhcp"}, false},
		{"valid with routes", IfaceConfig{
			Method: "static", Address: "192.168.1.10", Prefix: 24,
			Routes: []Route{
				{Destination: "100.64.0.0/24", Gateway: "192.168.1.1"},
				{Destination: "default", Gateway: "192.168.1.1"},
			},
		}, false},
		{"static missing address", IfaceConfig{Method: "static", Prefix: 24}, true},
		{"static bad address", IfaceConfig{Method: "static", Address: "not-an-ip", Prefix: 24}, true},
		{"static bad gateway", IfaceConfig{Method: "static", Address: "10.0.0.1", Prefix: 24, Gateway: "bad"}, true},
		{"bad method", IfaceConfig{Method: "pppoe"}, true},
		{"bad dns", IfaceConfig{Method: "dhcp", DNS: []string{"not-an-ip"}}, true},
		{"bad route destination", IfaceConfig{
			Method: "static", Address: "10.0.0.1", Prefix: 24,
			Routes: []Route{{Destination: "nope", Gateway: "10.0.0.1"}},
		}, true},
		{"bad route gateway", IfaceConfig{
			Method: "static", Address: "10.0.0.1", Prefix: 24,
			Routes: []Route{{Destination: "10.0.0.0/24", Gateway: "nope"}},
		}, true},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			err := tt.cfg.validate()
			if (err != nil) != tt.wantErr {
				t.Errorf("validate() error = %v, wantErr %v", err, tt.wantErr)
			}
		})
	}
}

func TestValidateIface(t *testing.T) {
	for _, tt := range []struct {
		name  string
		value string
		valid bool
	}{
		{name: "eth0", value: "eth0", valid: true},
		{name: "enp3s0", value: "enp3s0", valid: true},
		{name: "wlan0", value: "wlan0", valid: true},
		{name: "bridge", value: "br-lan", valid: true},
		{name: "veth", value: "veth1234567", valid: true},
		{name: "docker", value: "docker0", valid: true},
		{name: "empty", value: "", valid: false},
		{name: "leading dash", value: "-eth0", valid: false},
		{name: "path", value: "/dev/net", valid: false},
		{name: "space", value: "a b", valid: false},
		{name: "too long", value: "name_that_is_way_too_long_for_linux", valid: false},
	} {
		t.Run(tt.name, func(t *testing.T) {
			err := validateIface(tt.value)
			if tt.valid && err != nil {
				t.Errorf("validateIface(%q) unexpected error: %v", tt.value, err)
			}
			if !tt.valid && err == nil {
				t.Errorf("validateIface(%q) expected error", tt.value)
			}
		})
	}
}
