package license

import (
	"context"
	"errors"
	"net"
	"net/http"
	"testing"
	"time"
)

func TestAliDNSResolverUsesAliDNSInsteadOfSystemServer(t *testing.T) {
	var destination string
	resolver := newAliDNSResolver(func(_ context.Context, _ string, address string) (net.Conn, error) {
		destination = address
		client, server := net.Pipe()
		go server.Close()
		return client, nil
	})

	connection, err := resolver.Dial(context.Background(), "udp", "system-dns.example:53")
	if err != nil {
		t.Fatalf("Dial: %v", err)
	}
	connection.Close()
	if destination != aliDNSServers[0] {
		t.Fatalf("DNS destination = %q, want %q", destination, aliDNSServers[0])
	}
}

func TestAliDNSResolverFallsBackToSecondaryServer(t *testing.T) {
	var destinations []string
	resolver := newAliDNSResolver(func(_ context.Context, _ string, address string) (net.Conn, error) {
		destinations = append(destinations, address)
		if len(destinations) == 1 {
			return nil, errors.New("primary unavailable")
		}
		client, server := net.Pipe()
		go server.Close()
		return client, nil
	})

	connection, err := resolver.Dial(context.Background(), "udp", "system-dns.example:53")
	if err != nil {
		t.Fatalf("Dial: %v", err)
	}
	connection.Close()
	if len(destinations) != 2 || destinations[1] != aliDNSServers[1] {
		t.Fatalf("DNS destinations = %#v", destinations)
	}
}

func TestLicenseClientDisablesEnvironmentProxy(t *testing.T) {
	client := NewClient("http://127.0.0.1:8090", time.Second)
	transport, ok := client.httpClient.Transport.(*http.Transport)
	if !ok || transport.Proxy != nil {
		t.Fatal("license client must use a direct transport")
	}
}
