package metadata

import (
	"strings"

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

func (ms *MetadataService) buildRelationshipSnapshot(schemas []*models.ObjectMetadata, schemaMap map[string]*models.ObjectMetadata, explicitRelationships []*models.Relationship) (map[string][]*models.Relationship, map[string][]*models.ObjectMetadata) {
	relationshipsByChild := make(map[string][]*models.Relationship, len(schemas))
	childrenByParent := make(map[string][]*models.ObjectMetadata)
	explicitByChild := make(map[string][]*models.Relationship)

	for _, rel := range explicitRelationships {
		if rel == nil {
			continue
		}
		childKey := strings.ToLower(rel.ChildObjectAPIName)
		explicitByChild[childKey] = append(explicitByChild[childKey], rel)
	}

	for _, schema := range schemas {
		if schema == nil {
			continue
		}

		childKey := strings.ToLower(schema.APIName)
		relationshipsByChild[childKey] = metadatarel.ResolveEffectiveRelationships(schema, explicitByChild[childKey])

		seenParents := make(map[string]bool)
		for _, rel := range relationshipsByChild[childKey] {
			parentKey := strings.ToLower(rel.ParentObjectAPIName)
			if seenParents[parentKey] {
				continue
			}
			seenParents[parentKey] = true

			if childSchema := schemaMap[childKey]; childSchema != nil {
				childrenByParent[parentKey] = append(childrenByParent[parentKey], childSchema)
			}
		}
	}

	return relationshipsByChild, childrenByParent
}
