package records

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

// TestRecordExecutionUsesFailClosedMutationValidationRuleReads prevents a
// record write from silently returning to the display-oriented metadata API,
// where an absent request-bound view is intentionally represented as an empty
// result. Runtime mutation execution must use the profile-checked read path.
func TestRecordExecutionUsesFailClosedMutationValidationRuleReads(t *testing.T) {
	var mutationReads int
	err := filepath.WalkDir(".", func(path string, entry fs.DirEntry, walkErr error) error {
		if walkErr != nil {
			return walkErr
		}
		if entry.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
			return nil
		}
		file, err := parser.ParseFile(token.NewFileSet(), path, nil, 0)
		if err != nil {
			return err
		}
		ast.Inspect(file, func(node ast.Node) bool {
			selector, ok := node.(*ast.SelectorExpr)
			if !ok {
				return true
			}
			switch selector.Sel.Name {
			case "GetValidationRules":
				t.Errorf("%s uses fail-open GetValidationRules in record execution; use GetValidationRulesForMutation", path)
			case "GetValidationRulesForMutation":
				mutationReads++
			}
			return true
		})
		return nil
	})
	if err != nil {
		t.Fatal(err)
	}
	if mutationReads == 0 {
		t.Fatal("record execution has no fail-closed mutation validation-rule read")
	}
}
