package ip

import (
	"net"
	"reflect"
	"testing"
)

func TestGetPublicIp(t *testing.T) {
	tests := []struct {
		name    string
		list    []string
		want    string
		wantErr bool
	}{
		{"empty", []string{}, "", true},
		{"find", []string{"99.140.96.132"}, "99.140.96.132", false},
		{"findfirst", []string{"23.114.115.197", "251.78.128.148"}, "23.114.115.197", false},
		{"dontfindprivate", []string{"192.168.0.22", "88.12.32.44"}, "88.12.32.44", false},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			list := []net.Addr{}
			for _, item := range tt.list {
				list = append(list, &net.IPAddr{IP: net.ParseIP(item)})
			}

			want := net.ParseIP(tt.want)

			got, err := GetPublicIp(list)
			if (err != nil) != tt.wantErr {
				t.Errorf("GetPublicIp() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !reflect.DeepEqual(got, want) {
				t.Errorf("GetPublicIp() = %v, want %v", got, want)
			}
		})
	}
}

func TestAddrToIP(t *testing.T) {
	tests := []struct {
		name    string
		addr    net.Addr
		want    net.IP
		wantErr bool
	}{
		{"IPNet", &net.IPNet{IP: net.IPv4(177, 171, 44, 1)}, net.IPv4(177, 171, 44, 1), false},
		{"IPAddr", &net.IPAddr{IP: net.IPv4(240, 23, 119, 171)}, net.IPv4(240, 23, 119, 171), false},
		{"TCPAddr", &net.TCPAddr{IP: net.IPv4(139, 231, 35, 221)}, net.IPv4(139, 231, 35, 221), false},
		{"UDPAddr", &net.UDPAddr{IP: net.IPv4(167, 147, 140, 119)}, net.IPv4(167, 147, 140, 119), false},
		{"UnixAddr", &net.UnixAddr{}, nil, true},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := AddrToIP(tt.addr)

			if (err != nil) != tt.wantErr {
				t.Errorf("AddrToIP() error = %v, wantErr %v", err, tt.wantErr)
				return
			}

			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("AddrToIP() = %v, want %v", got, tt.want)
			}
		})
	}
}
