package schema

import (
	"strings"

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

// RollupChildDependency describes one parent rollup field whose value depends
// on writes to the given child object.
type RollupChildDependency struct {
	ParentObjectAPIName string
	RollupField         models.FieldMetadata
}

func canonicalRollupChildObjectKey(name string) string {
	return strings.ToLower(strings.TrimSpace(name))
}

// FindRollupChildDependencies returns every parent rollup field whose
// RollupConfig.SummaryObject points at childObjectAPIName.
//
// This is the authoritative metadata-derived read path for "can writes to this
// child object fan out into parent rollup recompute?" Records-layer
// transaction-boundary selection and analytics runtime reachability must both
// read through this helper rather than re-owning separate schema scans.
func FindRollupChildDependencies(allSchemas []*models.ObjectMetadata, childObjectAPIName string) []RollupChildDependency {
	childObjectKey := canonicalRollupChildObjectKey(childObjectAPIName)
	if childObjectKey == "" {
		return nil
	}

	var deps []RollupChildDependency
	for _, parentSchema := range allSchemas {
		if parentSchema == nil {
			continue
		}
		for _, field := range parentSchema.Fields {
			if field.RollupConfig == nil {
				continue
			}
			if canonicalRollupChildObjectKey(field.RollupConfig.SummaryObject) != childObjectKey {
				continue
			}
			deps = append(deps, RollupChildDependency{
				ParentObjectAPIName: parentSchema.APIName,
				RollupField:         field,
			})
		}
	}

	return deps
}

// HasRollupChildDependencies reports whether any parent rollup field depends on
// writes to childObjectAPIName.
func HasRollupChildDependencies(allSchemas []*models.ObjectMetadata, childObjectAPIName string) bool {
	return len(FindRollupChildDependencies(allSchemas, childObjectAPIName)) > 0
}
