package catalogpublication

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

func TestPublicationAuthorityHasNoProductionServingConsumer(t *testing.T) {
	_, file, _, ok := runtime.Caller(0)
	if !ok {
		t.Fatal("resolve test file")
	}
	packageDir := filepath.Dir(file)
	repoRoot := filepath.Dir(packageDir)
	allowedConsumers := map[string]bool{
		filepath.Join(repoRoot, "catalogapp", "schema.go"): true,
		// The phase-one producer is an explicit stopped-deployment lifecycle
		// operation. It does not attach the authority to request serving.
		filepath.Join(
			repoRoot,
			"catalogreconcile",
			"phase_one_publication.go",
		): true,
		filepath.Join(
			repoRoot,
			"catalogapp",
			"layout_bundle_owner_verification.go",
		): true,
		filepath.Join(
			repoRoot,
			"catalogtenant",
			"layout_bundle_owner_verification.go",
		): true,
		filepath.Join(
			repoRoot,
			"internal",
			"catalogsystem",
			"layout_bundle_owner_verification.go",
		): true,
	}
	importPath := []byte("nexuscrm-controlplane/catalogpublication")

	err := filepath.WalkDir(repoRoot, func(path string, entry os.DirEntry, walkErr error) error {
		if walkErr != nil {
			return walkErr
		}
		if entry.IsDir() {
			if entry.Name() == ".git" {
				return filepath.SkipDir
			}
			return nil
		}
		if filepath.Ext(path) != ".go" || strings.HasSuffix(path, "_test.go") ||
			allowedConsumers[path] || strings.HasPrefix(path, packageDir+string(filepath.Separator)) {
			return nil
		}
		raw, err := os.ReadFile(path)
		if err != nil {
			return err
		}
		if bytes.Contains(raw, importPath) {
			t.Errorf("production source wires the non-serving publication authority outside schema ownership: %s", path)
		}
		return nil
	})
	if err != nil {
		t.Fatal(err)
	}
}
