package formula

import (
	"strings"

	"github.com/nexuscrm/kernel/pkg/formula/spec"
)

// knownUnsupportedSalesforceImportFunctions are Salesforce formula functions
// seen in imported validation metadata but not implemented by the current
// runtime formula evaluator. The formula package owns this runtime-capability
// fact; metadata validation only decides whether to skip an imported rule whose
// unknown identifier is one of these known gaps.
var knownUnsupportedSalesforceImportFunctions = map[string]struct{}{
	"EXCLUDES":     {},
	"VLOOKUP":      {},
	"REGEX":        {},
	"GEOLOCATION":  {},
	"DISTANCE":     {},
	"CURRENCYRATE": {},
	"JSENCODE":     {},
	"URLENCODE":    {},
	"HTMLENCODE":   {},
	"ISTEXT":       {},
}

// IsKnownUnsupportedSalesforceImportFunction reports whether name is an
// explicit Salesforce-import formula gap for the default runtime function
// registry. Functions present in the runtime registry are never classified as
// unsupported, so adding native support or a base catalog entry automatically
// removes the skip classification.
func IsKnownUnsupportedSalesforceImportFunction(name string) bool {
	return isKnownUnsupportedSalesforceImportFunctionWithRegistry(name, runtimeFunctionRegistry)
}

// IsKnownUnsupportedSalesforceImportFunction reports against this engine's
// registry, including any runtime function bundles registered on the engine.
func (e *Engine) IsKnownUnsupportedSalesforceImportFunction(name string) bool {
	if e == nil || e.functionRegistry == nil {
		return IsKnownUnsupportedSalesforceImportFunction(name)
	}
	return isKnownUnsupportedSalesforceImportFunctionWithRegistry(name, e.functionRegistry)
}

func isKnownUnsupportedSalesforceImportFunctionWithRegistry(name string, registry *spec.Registry) bool {
	upper := strings.ToUpper(strings.TrimSpace(name))
	if upper == "" {
		return false
	}
	if registry == nil {
		registry = runtimeFunctionRegistry
	}
	if _, ok := registry.Lookup(upper); ok {
		return false
	}
	_, ok := knownUnsupportedSalesforceImportFunctions[upper]
	return ok
}
