package libbox

import (
	"context"
	"net/url"
	"os"
	"strings"
	"testing"
	"time"

	"github.com/sagernet/sing-box/common/certificate"
	"github.com/sagernet/sing-box/option"
	"github.com/sagernet/sing/common/logger"
)

type testPlatform struct{ resolvers string }

func (p testPlatform) Protect(fd int32) bool { return true }
func (p testPlatform) Resolvers() string     { return p.resolvers }

func TestGuestPathsAreTheAccountAPIOnly(t *testing.T) {
	for _, c := range []struct {
		method, path string
		want         bool
	}{
		{"GET", "/api/v1/plans", true}, {"POST", "/api/v1/login", true}, {"DELETE", "/api/v1/devices/abc", true},
		{"POST", "/api/v1/addons/turquoise/buy", true}, {"GET", "/api/v1/admin/users", false},
		{"GET", "/admin", false}, {"PUT", "/api/v1/me", false}, {"GET", "/api/v1/../admin", false}, {"GET", "/", false},
	} {
		if got := sangGuestPathAllowed(c.method, c.path); got != c.want {
			t.Errorf("%s %s: %v", c.method, c.path, got)
		}
	}
}

func TestTunnelResolversListTheNetworksOwnFirstWithoutDuplicatesOrLoopback(t *testing.T) {
	got := sangTunnelResolvers(testPlatform{"192.168.1.1, 127.0.0.1, ::1, 2.189.44.44, nonsense, 192.168.1.1"})
	if len(got) < 2 || got[0] != "192.168.1.1" || got[1] != "2.189.44.44" {
		t.Fatalf("%v", got)
	}
	seen := map[string]bool{}
	for _, r := range got {
		if seen[r] || r == "127.0.0.1" {
			t.Fatalf("%v", got)
		}
		seen[r] = true
	}
}

func TestTheBridgeKeepsItsPlainPathListAndAddsTheAddOn(t *testing.T) {
	if !sangAPIAllowed("GET", "/api/v1/addons/turquoise") || !sangAPIAllowed("POST", "/api/v1/addons/turquoise/buy") {
		t.Fatal("the add-on's endpoints are in the plain list")
	}
	if sangAPIAllowed("GET", "/api/v1/admin/users") || sangAPIAllowed("GET", "/api/v1/addons/other") {
		t.Fatal("nothing else is")
	}
}

func TestTurquoiseConfigDescribesTheShadowsocksWayThroughThePlugin(t *testing.T) {
	link := "ssdns://2022-blake3-aes-128-gcm%3AAAAAAAAAAAAAAAAAAAAAAA%3D%3D%3ABBBBBBBBBBBBBBBBBBBBBA%3D%3D@tunnel.example.com/?pub=" + strings.Repeat("a", 64) + "&r=1.2.3.4%2C5.6.7.8#N"
	config, err := sangTurquoiseConfig(link, testPlatform{"192.168.1.1"})
	if err != nil {
		t.Fatal(err)
	}
	for _, want := range []string{`"plugin":"sang-dnstt"`, `"network":"tcp"`, "domain=tunnel.example.com", "resolvers=192.168.1.1,", "1.2.3.4"} {
		if !strings.Contains(config, want) {
			t.Errorf("missing %s in %s", want, config)
		}
	}
	ctx := baseContext(nil)
	if _, err := parseConfig(ctx, config); err != nil {
		t.Fatalf("the engine does not accept it: %v", err)
	}
	for _, bad := range []string{"vless://x@y:443", "ssdns://x@y/", "ssdns://a:b@y/?r=1.2.3.4"} {
		if _, err := sangTurquoiseConfig(bad, testPlatform{}); err == nil {
			t.Errorf("accepted %s", bad)
		}
	}
}

// Opt-in (SANG_LIVE=1): the account API through the real DNS tunnel.
func TestLiveGuestRequest(t *testing.T) {
	if os.Getenv("SANG_LIVE") != "1" {
		t.Skip("set SANG_LIVE=1 for the network check")
	}
	u, _ := url.Parse("/api/v1/plans")
	roots, err := certificate.NewStore(context.Background(), logger.NOP(), option.CertificateOptions{})
	if err != nil {
		t.Fatal(err)
	}
	defer roots.Close()
	for i := 0; i < 3; i++ {
		started := time.Now()
		// The tunnel itself, whatever the plain routes would do.
		result := sangGuestRequest("GET", u, "", "", testPlatform{os.Getenv("SANG_RESOLVERS")}, roots.Pool())
		if result == nil || result.Status != 200 || !strings.Contains(result.Body, `"currency":"SANG"`) {
			t.Fatalf("call %d: %v", i+1, result)
		}
		t.Logf("call %d answered: %d bytes in %v", i+1, len(result.Body), time.Since(started).Round(time.Millisecond))
	}
	if !sangGuestPreferred() {
		t.Fatal("after an answer the tunnel leads for a while")
	}
}
