package license

import (
	"context"
	"fmt"
	"net"
	"net/http"
)

var aliDNSServers = []string{
	"223.5.5.5:53",
	"223.6.6.6:53",
}

type dnsDialContext func(context.Context, string, string) (net.Conn, error)

func newAliDNSResolver(dial dnsDialContext) *net.Resolver {
	if dial == nil {
		dialer := &net.Dialer{}
		dial = dialer.DialContext
	}
	return &net.Resolver{
		PreferGo: true,
		Dial: func(ctx context.Context, network, _ string) (net.Conn, error) {
			return dialAliDNS(ctx, network, dial)
		},
	}
}

func dialAliDNS(ctx context.Context, network string, dial dnsDialContext) (net.Conn, error) {
	var lastErr error
	for _, server := range aliDNSServers {
		connection, err := dial(ctx, network, server)
		if err == nil {
			return connection, nil
		}
		lastErr = err
	}
	return nil, fmt.Errorf("connect to AliDNS: %w", lastErr)
}

func newLicenseHTTPTransport() *http.Transport {
	transport := http.DefaultTransport.(*http.Transport).Clone()
	transport.Proxy = nil
	dialer := &net.Dialer{Resolver: newAliDNSResolver(nil)}
	transport.DialContext = dialer.DialContext
	return transport
}
