package catalogapp

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

// TestPublishedPackageIsConsumableWithoutCoreReplaces reproduces the production
// build boundary that a clean external module sees. Go intentionally ignores
// replace directives declared by dependency modules, so the only replace below
// locates this not-yet-published controlplane checkout; no NexusCRM core
// replacement is available to hide a production 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()
	writeTestFile(t, filepath.Join(consumer, "go.mod"), `module example.com/catalogapp-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")
	writeTestFile(t, filepath.Join(consumer, "main.go"), `package main

import (
	"context"

	"github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/securityprojectionv1"
	"github.com/pingcap-inc/nexuscrm-controlplane/catalogapp"
)

type writer struct{}

func (writer) ActivateProjection(context.Context, uint64, securityprojectionv1.Projection) error {
	return nil
}

var _ catalogapp.RuntimeProjectionWriter = writer{}

func main() {
	_ = catalogapp.HandlerBinding{}
	_ = catalogapp.RuntimeSecurityProjection{}
}
`)

	// Build the consumer's production graph directly. `go mod tidy` is not a
	// faithful release probe for a local replacement: it also loads tests from
	// the replaced dependency under every build tag, even though consumers never
	// compile those repository-internal tests. -mod=mod records only the modules
	// needed by the production build while still failing on an unavailable or
	// forbidden production dependency.
	runExternalGo(t, consumer, "build", "-mod=mod", "./...")
	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 runExternalGo(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 writeTestFile(t *testing.T, path, content string) {
	t.Helper()
	if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
		t.Fatal(err)
	}
}
