package constants

import (
	"context"
	"strings"
)

const (
	// FormulaContextSystemContext is the validation/flow formula global that
	// exposes platform-owned execution facts without overloading Salesforce
	// session globals such as $User or $Profile.
	FormulaContextSystemContext = "__SystemContext"

	FormulaSystemContextIsDerivedRecompute  = "IsDerivedRecompute"
	FormulaSystemContextConnectorSyncOrigin = "ConnectorSyncOrigin"
)

type formulaSystemContextKey string

const formulaSystemContextKeyDerivedRecompute formulaSystemContextKey = "formula_derived_recompute"

func WithFormulaDerivedRecompute(ctx context.Context) context.Context {
	return context.WithValue(ctx, formulaSystemContextKeyDerivedRecompute, true)
}

func IsFormulaDerivedRecompute(ctx context.Context) bool {
	if ctx == nil {
		return false
	}
	v, _ := ctx.Value(formulaSystemContextKeyDerivedRecompute).(bool)
	return v
}

func FormulaSystemContextFromContext(ctx context.Context) map[string]interface{} {
	return map[string]interface{}{
		FormulaSystemContextIsDerivedRecompute:  IsFormulaDerivedRecompute(ctx),
		FormulaSystemContextConnectorSyncOrigin: ConnectorSyncOriginFromContext(ctx),
	}
}

func ConnectorSyncOriginFromContext(ctx context.Context) string {
	if ctx == nil {
		return ""
	}
	origin, _ := ctx.Value(ContextKeyConnectorSyncOrigin).(string)
	return strings.ToLower(strings.TrimSpace(origin))
}
