package builder

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestInjectPolymorphCreatesFile(t *testing.T) {
	dir := t.TempDir()
	ldflags, err := injectPolymorph(dir, "test-seed-123")
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(ldflags, "-buildid=") || !strings.Contains(ldflags, "-X main.polymorphNonce=") {
		t.Fatalf("unexpected ldflags: %q", ldflags)
	}
	deadcode := filepath.Join(dir, "polymorph", "deadcode.go")
	raw, err := os.ReadFile(deadcode)
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(string(raw), "package polymorph") {
		t.Fatal("deadcode.go missing package")
	}
	if !strings.Contains(string(raw), "test-seed-123") {
		t.Fatal("seed not embedded")
	}
}

func TestInjectPolymorphEmptySeed(t *testing.T) {
	dir := t.TempDir()
	_, err := injectPolymorph(dir, "")
	if err != nil {
		t.Fatal(err)
	}
}

func TestPickServiceMasqueradeDeterministic(t *testing.T) {
	n1, d1 := pickServiceMasquerade("build-abc")
	n2, d2 := pickServiceMasquerade("build-abc")
	if n1 != n2 || d1 != d2 {
		t.Fatalf("masquerade should be deterministic: (%s,%s) vs (%s,%s)", n1, d1, n2, d2)
	}
	if n1 == "" || d1 == "" {
		t.Fatal("expected non-empty masquerade profile")
	}
}

func TestPickServiceMasqueradeVariesBySeed(t *testing.T) {
	seen := map[string]bool{}
	for i := 0; i < 20; i++ {
		name, _ := pickServiceMasquerade(string(rune('a' + i)))
		seen[name] = true
	}
	if len(seen) < 2 {
		t.Fatal("expected different masquerade names across seeds")
	}
}

func TestServiceMasqueradeHelpers(t *testing.T) {
	req := &BuildRequest{RunAs: "service"}
	if !serviceMasqueradeEnabled(req) {
		t.Fatal("service run-as should enable masquerade")
	}
	name := serviceMasqueradeName("bid", req)
	donor := serviceMasqueradeDonor("bid", req)
	if name == "" || donor == "" {
		t.Fatalf("expected masquerade name/donor, got %q / %q", name, donor)
	}
	userReq := &BuildRequest{RunAs: "user"}
	if serviceMasqueradeName("bid", userReq) != "" {
		t.Fatal("user run-as should not masquerade")
	}
}
