package metadata

import (
	"context"
	"log"
	"strings"

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

// GetSharingParentRelationship returns the persisted relationship row that
// marks a child object as ControlledByParent. This keeps sharing-parent shape
// resolution inside metadata service so permission paths do not scan the
// relationship graph independently.
func (ms *MetadataService) GetSharingParentRelationship(ctx context.Context, childObjectAPIName string) *models.Relationship {
	if err := ms.ensureCoreCacheInitialized(ctx); err != nil {
		log.Printf("⚠️ Failed to initialize core cache in GetSharingParentRelationship(%s): %v", childObjectAPIName, err)
		return nil
	}

	snap := ms.loadCoreCache()
	if snap == nil {
		return nil
	}

	for _, rel := range snap.relationshipsMap[strings.ToLower(childObjectAPIName)] {
		if rel == nil {
			continue
		}
		if !rel.IsSharingParent {
			continue
		}
		if !strings.EqualFold(rel.ChildObjectAPIName, childObjectAPIName) {
			continue
		}
		return rel
	}

	return nil
}
