package catalogread

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

// TestPublishedPackageIsConsumableWithoutCoreReplaces reproduces the release
// boundary that a clean external Runtime consumer sees. The only replacement
// locates this not-yet-published controlplane checkout; no NexusCRM core
// module may hide a workspace-only dependency.
func TestPublishedPackageIsConsumableWithoutCoreReplaces(t *testing.T) {
	_, source, _, ok := runtime.Caller(0)
	if !ok {
		t.Fatal("locate package source")
	}
	moduleRoot := filepath.Dir(filepath.Dir(source))
	consumer := t.TempDir()
	writeReleaseProbeFile(t, filepath.Join(consumer, "go.mod"), `module example.com/catalogread-release-probe

go 1.25.0

require github.com/pingcap-inc/nexuscrm-controlplane v0.0.0

replace github.com/pingcap-inc/nexuscrm-controlplane => `+moduleRoot+"\n")
	writeReleaseProbeFile(t, filepath.Join(consumer, "main.go"), `package main

import "github.com/pingcap-inc/nexuscrm-controlplane/catalogread"

func main() {
	_ = catalogread.ServingCapability{}
	_ = catalogread.ServingInstallation{}
	_ = catalogread.ServingHandlerBinding{}
}
`)

	runReleaseProbeGo(t, consumer, "mod", "tidy")
	runReleaseProbeGo(t, consumer, "build", "./...")
	resolved, err := os.ReadFile(filepath.Join(consumer, "go.mod"))
	if err != nil {
		t.Fatal(err)
	}
	for _, forbidden := range []string{"github.com/nexuscrm/", "github.com/pingcap-inc/NexusCRM/"} {
		if strings.Contains(string(resolved), forbidden) {
			t.Fatalf("external consumer acquired forbidden core dependency %q:\n%s", forbidden, resolved)
		}
	}
}

func runReleaseProbeGo(t *testing.T, dir string, args ...string) {
	t.Helper()
	command := exec.Command("go", args...)
	command.Dir = dir
	command.Env = append(os.Environ(),
		"GOWORK=off",
		"GOPRIVATE=github.com/pingcap-inc/*",
		"GONOSUMDB=github.com/pingcap-inc/*",
		"GOPROXY=direct",
	)
	if output, err := command.CombinedOutput(); err != nil {
		t.Fatalf("go %s: %v\n%s", strings.Join(args, " "), err, output)
	}
}

func writeReleaseProbeFile(t *testing.T, path, content string) {
	t.Helper()
	if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
		t.Fatal(err)
	}
}
