package flowauthoring

import (
	"fmt"
	"strings"

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

const LegacyEmailAlertActionType = "emailAlert"

// ValidateNoLegacyEmailAlertActionCalls blocks post-cutover Flow metadata from
// authoring dependencies on the retired WorkflowAlert runtime dispatch path.
func ValidateNoLegacyEmailAlertActionCalls(meta models.FlowMetadata) error {
	for i, action := range meta.ActionCalls {
		if !strings.EqualFold(strings.TrimSpace(action.ActionType), LegacyEmailAlertActionType) {
			continue
		}
		actionLabel := firstNonEmpty(strings.TrimSpace(action.Name), strings.TrimSpace(action.ActionName), fmt.Sprintf("actionCalls[%d]", i))
		return fmt.Errorf("actionCalls[%d] %q uses retired actionType=emailAlert; migrate this WorkflowAlert dependency to canonical Flow sendEmail or remove it before saving", i, actionLabel)
	}
	return nil
}

func firstNonEmpty(candidates ...string) string {
	for _, candidate := range candidates {
		if candidate != "" {
			return candidate
		}
	}
	return ""
}
