package boundary_test

import (
	"io/fs"
	"path/filepath"
	"strings"
	"testing"
)

func TestRuntimeDelegationFieldInventoryHasOneDesignOwner(t *testing.T) {
	root := repoRoot(t)
	designDir := filepath.Join(root, "docs", "design")
	canonicalPath := filepath.Join(designDir, "runtime-trusted-delegation-contract.md")
	canonicalLink := "runtime-trusted-delegation-contract.md#4-delegation-facts"

	// This contiguous sequence identifies the exact signed-delegation claim
	// inventory without banning legitimate prose about any individual fact.
	// The inventory belongs only to the capability ADR; higher-level and
	// consumer documents must link to it.
	inventorySignature := "OrgID\nPrincipalID\nSessionID\nCallerWorkloadID\nAppInstallationID"
	var owners []string
	err := filepath.WalkDir(designDir, func(path string, entry fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		if entry.IsDir() || filepath.Ext(path) != ".md" {
			return nil
		}
		if strings.Contains(readFile(t, path), inventorySignature) {
			owners = append(owners, displayPath(root, path))
		}
		return nil
	})
	if err != nil {
		t.Fatalf("walk design docs: %v", err)
	}
	wantOwner := displayPath(root, canonicalPath)
	if len(owners) != 1 || owners[0] != wantOwner {
		t.Fatalf("signed delegation inventory owners = %v, want only %s", owners, wantOwner)
	}

	for _, name := range []string{
		"nexuscrm-serviceification-target-architecture.md",
		"runtime-selected-record-read-contract.md",
	} {
		body := readFile(t, filepath.Join(designDir, name))
		if !strings.Contains(body, canonicalLink) {
			t.Fatalf("%s must route delegation facts to %s", name, canonicalLink)
		}
		for _, stale := range []string{
			"ScopesOrCapabilities",
			"issues short-lived delegation containing:",
			"Audience / Scopes",
		} {
			if strings.Contains(body, stale) {
				t.Fatalf("%s retains superseded delegation inventory marker %q", name, stale)
			}
		}
	}
}
