package server

import (
	"context"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
	apiv1 "github.com/tidbcloud/cluster-service-ng/api/cluster-service-ng/v1beta"
	"github.com/tidbcloud/cluster-service-ng/domain/entity"
	dataplanemocks "github.com/tidbcloud/cluster-service-ng/pkg/dataplane/mocks"
	kubemocks "github.com/tidbcloud/cluster-service-ng/pkg/externalmocks/mocks"
	schemav1 "github.com/tidbcloud/cluster-service-ng/pkg/storage/etcd/schema/v1"
	repomocks "github.com/tidbcloud/cluster-service-ng/pkg/storage/repo/mocks"
	autoscalingv2 "k8s.io/api/autoscaling/v2"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func TestGetHPASpecStripsTiProxyGroupPrefix(t *testing.T) {
	sharedPoolRepo := repomocks.NewSharedPoolRepo(t)
	dataplaneManager := dataplanemocks.NewManager(t)
	kubeclient := kubemocks.NewClient(t)

	sharedPoolRepo.On("Load", mock.Anything, "test-sharedpool-id", false).Return(&entity.SharedPool{
		SharedPool: apiv1.SharedPool{
			Id:            "test-sharedpool-id",
			DataplaneName: "test-dataplane",
		},
	}, nil)
	dataplaneManager.On("GetClient", "test-dataplane").Return(kubeclient, nil)
	kubeclient.On("List", mock.Anything, mock.IsType(&autoscalingv2.HorizontalPodAutoscalerList{}), mock.Anything).
		Run(func(args mock.Arguments) {
			hpaList := args.Get(1).(*autoscalingv2.HorizontalPodAutoscalerList)
			hpaList.Items = []autoscalingv2.HorizontalPodAutoscaler{
				{
					ObjectMeta: metav1.ObjectMeta{
						Labels: map[string]string{
							schemav1.LabelComponentKey:    "tiproxy",
							schemav1.LabelPingcapGroupKey: "db-cluster-a",
						},
					},
				},
			}
		}).
		Return(nil)

	server := &serverImpl{
		sharedPoolRepo:   sharedPoolRepo,
		dataplaneManager: dataplaneManager,
	}

	specs, err := server.GetHPASpec(context.Background(), "test-sharedpool-id")
	require.NoError(t, err)
	require.Len(t, specs, 1)
	assert.Equal(t, apiv1.ComponentType_TIPROXY, specs[0].GetComponentType())
	assert.Equal(t, "cluster-a", specs[0].GetId())
}
