package metadata

import (
	"context"
	"log"
	"strings"
)

// ForeignKeyForRelationship resolves a relationship name to the child object's
// lookup/master-detail field through MetadataService's materialized
// relationship snapshot.
func (ms *MetadataService) ForeignKeyForRelationship(ctx context.Context, objectAPIName, relationshipName string) (string, bool) {
	objectKey := strings.ToLower(strings.TrimSpace(objectAPIName))
	relationshipName = strings.TrimSpace(relationshipName)
	relationshipKey := strings.ToLower(relationshipName)
	if objectKey == "" || relationshipKey == "" {
		return "", false
	}
	if ms.UsesRequestBoundRuntimeView() {
		view, ok := ms.runtimeView(ctx)
		if !ok || view == nil {
			return "", false
		}
		for _, relationship := range view.RelationshipsForChild(objectAPIName) {
			if strings.EqualFold(strings.TrimSpace(relationship.RelationshipName), relationshipName) {
				return relationship.FieldAPIName, true
			}
		}
		return "", false
	}
	if err := ms.ensureCoreCacheInitialized(ctx); err != nil {
		log.Printf("Warning: failed to initialize core cache in ForeignKeyForRelationship(%s, %s): %v", objectAPIName, relationshipName, err)
		return "", false
	}

	snap := ms.loadCoreCache()
	if snap == nil {
		return "", false
	}
	for _, rel := range snap.relationshipsMap[objectKey] {
		if rel == nil || !strings.EqualFold(strings.TrimSpace(rel.RelationshipName), relationshipName) {
			continue
		}
		return rel.FieldAPIName, true
	}
	return "", false
}

// TargetObjectsForForeignKey resolves the parent object target(s) for a child
// object's lookup/master-detail field through MetadataService's materialized
// relationship snapshot.
func (ms *MetadataService) TargetObjectsForForeignKey(ctx context.Context, objectAPIName, foreignKey string) ([]string, bool) {
	objectKey := strings.ToLower(strings.TrimSpace(objectAPIName))
	foreignKey = strings.TrimSpace(foreignKey)
	foreignKeyKey := strings.ToLower(foreignKey)
	if objectKey == "" || foreignKeyKey == "" {
		return nil, false
	}
	if ms.UsesRequestBoundRuntimeView() {
		view, ok := ms.runtimeView(ctx)
		if !ok || view == nil {
			return nil, false
		}
		var targets []string
		for _, relationship := range view.RelationshipsForChild(objectAPIName) {
			if strings.EqualFold(strings.TrimSpace(relationship.FieldAPIName), foreignKey) {
				targets = append(targets, relationship.ParentObjectAPIName)
			}
		}
		return targets, len(targets) != 0
	}
	if err := ms.ensureCoreCacheInitialized(ctx); err != nil {
		log.Printf("Warning: failed to initialize core cache in TargetObjectsForForeignKey(%s, %s): %v", objectAPIName, foreignKey, err)
		return nil, false
	}

	snap := ms.loadCoreCache()
	if snap == nil {
		return nil, false
	}
	var targets []string
	for _, rel := range snap.relationshipsMap[objectKey] {
		if rel == nil || !strings.EqualFold(strings.TrimSpace(rel.FieldAPIName), foreignKey) {
			continue
		}
		targets = append(targets, rel.ParentObjectAPIName)
	}
	if len(targets) == 0 {
		return nil, false
	}
	return targets, true
}
