package utils

import (
	"encoding/hex"
	"fmt"
	"strconv"

	"crypto/md5" //nolint:gosec

	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

func WrapError(ctx string, err error) error {
	if err == nil {
		return fmt.Errorf("%s", ctx)
	}
	return fmt.Errorf("%s: %v", ctx, err)
}

func GetAnnotation(obj client.Object, key string) string {
	annotations := obj.GetAnnotations()
	if annotations == nil {
		return ""
	}
	return annotations[key]
}

func SetAnnotation(obj client.Object, key, value string) {
	annotations := obj.GetAnnotations()
	if annotations == nil {
		annotations = make(map[string]string)
	}
	annotations[key] = value
	obj.SetAnnotations(annotations)
}

func GetLabel(obj client.Object, key string) string {
	labels := obj.GetLabels()
	if labels == nil {
		return ""
	}
	return labels[key]
}

func SetLabel(obj client.Object, key, value string) {
	labels := obj.GetLabels()
	if labels == nil {
		labels = make(map[string]string)
	}
	labels[key] = value
	obj.SetLabels(labels)
}

// IsStatusConditionTrue returns true when the conditionType is present and set to `true`
func IsStatusConditionTrue(conditions []appsv1.DeploymentCondition, conditionType appsv1.DeploymentConditionType) bool {
	return IsStatusConditionPresentAndEqual(conditions, conditionType, corev1.ConditionTrue)
}

// IsStatusConditionPresentAndEqual returns true when conditionType is present and equal to status.
func IsStatusConditionPresentAndEqual(conditions []appsv1.DeploymentCondition, conditionType appsv1.DeploymentConditionType, status corev1.ConditionStatus) bool {
	for _, condition := range conditions {
		if condition.Type == conditionType {
			return condition.Status == status
		}
	}
	return false
}

func GetHashNums(s string) int64 {
	hash := md5.Sum([]byte(s)) //nolint:gosec
	hashStr := hex.EncodeToString(hash[:])
	hashStr = hashStr[:8]
	hashInt, err := strconv.ParseInt(hashStr, 16, 64)
	if err != nil {
		fmt.Println("Error converting hash to int:", err)
		return -1
	}
	return hashInt
}
