package sfcrmappservice

import (
	"go/parser"
	"go/token"
	"io/fs"
	"path/filepath"
	"strconv"
	"strings"
	"testing"
)

// TestAppServiceUsesOnlyPublishedDownwardPorts guards every current and future
// subpackage. The independently deployed L1 process may consume released L0
// contracts/host primitives, but never the NexusCRM monolith, a database, the
// transitional in-process dialect, or an L2 delivery package.
func TestAppServiceUsesOnlyPublishedDownwardPorts(t *testing.T) {
	t.Helper()
	forbiddenPrefixes := []string{
		"github.com/nexuscrm/",
		"github.com/pingcap-inc/nexuscrm-app-packs/dialects/",
		"github.com/pingcap-inc/nexuscrm-controlplane",
		"github.com/pingcap-inc/nexuscrm-pingcap-pack",
	}
	err := filepath.WalkDir(".", func(path string, entry fs.DirEntry, walkErr error) error {
		if walkErr != nil {
			return walkErr
		}
		if entry.IsDir() || filepath.Ext(path) != ".go" {
			return nil
		}
		parsed, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
		if err != nil {
			return err
		}
		for _, spec := range parsed.Imports {
			importPath, err := strconv.Unquote(spec.Path.Value)
			if err != nil {
				return err
			}
			if importPath == "database/sql" {
				t.Errorf("%s imports database/sql; AppService must call Runtime", path)
			}
			for _, prefix := range forbiddenPrefixes {
				if strings.HasPrefix(importPath, prefix) {
					t.Errorf("%s imports forbidden upward/sideways dependency %q", path, importPath)
				}
			}
		}
		return nil
	})
	if err != nil {
		t.Fatal(err)
	}
}
