package templateversion

import (
	"context"
	"fmt"
	"strings"

	"github.com/tidbcloud/cluster-service-ng/pkg/template/render"
)

// annotatable is an interface for objects that support annotations (both typed and unstructured K8s objects).
type annotatable interface {
	GetAnnotations() map[string]string
	SetAnnotations(annotations map[string]string)
}

// RenderWithVersion renders a template with version resolution.
// It returns the rendered YAML string and the resolved template name/version for annotations.
func RenderWithVersion(
	ctx context.Context,
	svc *Service,
	templName, templVersion string,
	templArgs map[string]string,
) (yamlStr, resolvedName, resolvedVersion string, err error) {
	if svc == nil {
		return "", "", "", fmt.Errorf("templateVersionSvc is nil, cannot resolve template %s", templName)
	}

	template := strings.TrimSpace(templName)

	resolvedName, resolvedVersion, templateContent, err := svc.Resolve(ctx, template, templVersion)
	if err != nil {
		return "", "", "", fmt.Errorf("failed to resolve template %s: %w", template, err)
	}

	yamlStr = render.RenderContent(templateContent, templArgs)
	return yamlStr, resolvedName, resolvedVersion, nil
}

// SetVersionAnnotations sets template version annotations on a Kubernetes object.
// If resolvedName is empty, no annotations are set.
func SetVersionAnnotations(obj annotatable, resolvedName, resolvedVersion string) {
	if obj == nil || resolvedName == "" {
		return
	}
	annotations := obj.GetAnnotations()
	if annotations == nil {
		annotations = map[string]string{}
	}
	annotations[TemplateNameAnnotationKey] = resolvedName
	annotations[TemplateVersionAnnotationKey] = resolvedVersion
	obj.SetAnnotations(annotations)
}
