package schemautil

import (
	"sort"

	"github.com/nexuscrm/shared/pkg/constants"
	"github.com/nexuscrm/shared/pkg/models"
)

// FieldRequiresCreateInput reports the schema's initial caller-input demand.
// It does not evaluate supplied values, compound components, or later validation
// rules. Records owns those payload-dependent checks; metadata projections use
// this same predicate to describe the static demand without executing a create.
func FieldRequiresCreateInput(field *models.FieldMetadata) bool {
	if field == nil || !field.Required || !field.Createable || field.DefaultedOnCreate ||
		(field.DefaultValue != nil && *field.DefaultValue != "") {
		return false
	}
	switch constants.NormalizeFieldType(string(field.Type)) {
	case constants.FieldTypeAutonumber, constants.FieldTypeFormula, constants.FieldTypeRollupSummary:
		return false
	}
	return true
}

// RequiredCreateInputFields returns the canonical, independently owned names of
// fields with initial caller-input demand. An empty result is known and non-nil.
func RequiredCreateInputFields(schema *models.ObjectMetadata) []string {
	required := make([]string, 0)
	if schema != nil {
		for i := range schema.Fields {
			if FieldRequiresCreateInput(&schema.Fields[i]) {
				required = append(required, schema.Fields[i].APIName)
			}
		}
	}
	sort.Strings(required)
	return required
}
