package standardaction

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

// The standard-action engine is app-blind. As of L0-E PR-2 the Reject* reason
// constants hold NEUTRAL snake_case values; the Salesforce v63 wire spelling
// (INVALID_REQUEST, REQUIRED_FIELD_MISSING, ...) is rendered by the dialect
// (dialect-sf-crm/standard_actions.go standardActionReasonToSFCode).
//
// This seal fails if any of the five UPPERCASE Salesforce error-code spellings
// regrow anywhere in the standardaction package source, which would re-couple the
// engine to the SF wire dialect. The forbidden spellings are assembled from
// fragments so this seal file does not itself contain the literals it forbids.
func forbiddenSFRejectSpellings() []string {
	// Build each spelling from pieces so this file never contains the literal.
	return []string{
		strings.Join([]string{"INVALID", "REQUEST"}, "_"),
		strings.Join([]string{"REQUIRED", "FIELD", "MISSING"}, "_"),
		strings.Join([]string{"INVALID", "FIELD"}, "_"),
		strings.Join([]string{"INSUFFICIENT", "PERMISSIONS"}, "_"),
		strings.Join([]string{"UNKNOWN", "EXCEPTION"}, "_"),
	}
}

func TestRejectReasonSpellingsStayNeutral(t *testing.T) {
	_, here, _, ok := runtime.Caller(0)
	if !ok {
		t.Fatal("runtime.Caller failed")
	}
	pkgDir := filepath.Dir(here)
	selfBase := filepath.Base(here)
	forbidden := forbiddenSFRejectSpellings()

	entries, err := os.ReadDir(pkgDir)
	if err != nil {
		t.Fatalf("read package dir %s: %v", pkgDir, err)
	}

	for _, entry := range entries {
		if entry.IsDir() {
			continue
		}
		name := entry.Name()
		if !strings.HasSuffix(name, ".go") || name == selfBase {
			continue
		}
		raw, err := os.ReadFile(filepath.Join(pkgDir, name))
		if err != nil {
			t.Fatalf("read %s: %v", name, err)
		}
		src := string(raw)
		for _, spelling := range forbidden {
			if strings.Contains(src, spelling) {
				t.Fatalf("Salesforce reason spelling %q regrew in the app-blind standardaction engine (file %s); render it in the dialect instead", spelling, name)
			}
		}
	}
}
