/*
Copyright 2024.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
See the License for the specific language governing permissions and
limitations under the License.
*/

package clusterupgradeoperation

import (
	"context"

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

	"github.com/tidbcloud/observability/pkg/resourceworker/controllers/clusterupgradeoperation/providers"
)

// GetNodeGroupVersionFromNodes returns the nodegroup version by listing nodes and checking
// kubelet version. Only returns a version when all nodes have the same version.
// Used when cloud API does not provide version (e.g. ACK NodeComponents empty).
func GetNodeGroupVersionFromNodes(
	ctx context.Context,
	cli client.Client,
	provider providers.CloudProviderInterface,
	clusterName string,
	nodeGroup *providers.NodeGroup,
) string {
	labelSelector, err := provider.GetNodeGroupLabelSelector(ctx, clusterName, nodeGroup.ID)
	if err != nil {
		return ""
	}
	nodeList := &corev1.NodeList{}
	if err := cli.List(ctx, nodeList, client.MatchingLabels(labelSelector)); err != nil || len(nodeList.Items) == 0 {
		return ""
	}
	first := nodeList.Items[0].Status.NodeInfo.KubeletVersion
	for i := 1; i < len(nodeList.Items); i++ {
		if nodeList.Items[i].Status.NodeInfo.KubeletVersion != first {
			return "" // nodes have different versions, e.g. during rolling upgrade
		}
	}
	return first
}
