package action

import (
	"testing"

	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
	apiv1 "github.com/tidbcloud/cluster-service-ng/api/cluster-service-ng/v1beta"
	dplanemgrv1 "github.com/tidbcloud/cluster-service-ng/api/dataplane-manager/v1"
	"github.com/tidbcloud/cluster-service-ng/domain/entity"
	"github.com/tidbcloud/cluster-service-ng/domain/workflow"
	dataplanemgrmocks "github.com/tidbcloud/cluster-service-ng/pkg/dataplanemgr/mocks"
	"github.com/tidbcloud/cluster-service-ng/pkg/runtime/actions"
	repomocks "github.com/tidbcloud/cluster-service-ng/pkg/storage/repo/mocks"
	"google.golang.org/protobuf/types/known/emptypb"
)

func TestDeleteLoadBalanceActionDeletesLoadBalancersWhenTiProxyComponentMissing(t *testing.T) {
	sharedPoolRepo := repomocks.NewSharedPoolRepo(t)
	tidbGroupRepo := repomocks.NewTiDBGroupRepo(t)
	client := dataplanemgrmocks.NewClient(t)

	sharedPool := &entity.SharedPool{
		SharedPool: apiv1.SharedPool{
			Id:            "shared-pool-1",
			DataplaneName: "dataplane-1",
			ComponentGroups: []*entity.Component{
				{
					Id:            "cluster-2",
					ComponentType: apiv1.ComponentType_TIPROXY,
				},
			},
		},
	}
	tidbGroup := &entity.TiDBGroup{
		TiDBGroup: apiv1.TiDBGroup{
			Id:            "tidb-group-1",
			ClusterId:     "cluster-1",
			SharedPoolId:  "shared-pool-1",
			DataplaneName: "dataplane-1",
		},
	}

	tidbGroupRepo.On("Load", mock.Anything, "tidb-group-1", true).Return(tidbGroup, nil).Once()
	sharedPoolRepo.On("Load", mock.Anything, "shared-pool-1", false).Return(sharedPool, nil).Once()
	client.On("DeleteLoadBalancer", mock.Anything, mock.MatchedBy(func(req *dplanemgrv1.DeleteLoadBalancerRequest) bool {
		return req.GetDataPlaneId() == "dataplane-1" && req.GetId() == entity.GetPublicSvcName("tidb-group-1")
	})).Return(&emptypb.Empty{}, nil).Once()
	client.On("DeleteLoadBalancer", mock.Anything, mock.MatchedBy(func(req *dplanemgrv1.DeleteLoadBalancerRequest) bool {
		return req.GetDataPlaneId() == "dataplane-1" && req.GetId() == entity.GetPrivateSvcName("tidb-group-1")
	})).Return(&emptypb.Empty{}, nil).Once()

	action := NewDeleteLoadBalanceAction(sharedPoolRepo, tidbGroupRepo, client)

	err := action.Invoke(actions.ActionArgs{
		workflow.SharedPoolIdKey: actions.ActionArgString("shared-pool-1"),
		workflow.TiDBGroupIdKey:  actions.ActionArgString("tidb-group-1"),
	})

	require.NoError(t, err)
}
