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"
	bractionmocks "github.com/tidbcloud/cluster-service-ng/domain/workflow/action/br/mocks"
	executormocks "github.com/tidbcloud/cluster-service-ng/pkg/runtime/executor/mocks"
	repomnocks "github.com/tidbcloud/cluster-service-ng/pkg/storage/repo/mocks"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func TestGetTiDBCluster(t *testing.T) {
	tests := []struct {
		name          string
		tidbClusterId string
		setupMocks    func(*repomnocks.TiDBClusterRepo, *repomnocks.SharedPoolRepo, *repomnocks.TiDBGroupRepo, *executormocks.RemoteExecutor, *bractionmocks.ScaleManager)
		expectedError string
		expectedCode  codes.Code
		validate      func(*testing.T, *entity.TiDBCluster, error)
	}{
		{
			name:          "successful get tidb cluster",
			tidbClusterId: "testclusterid",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, dagExecutor *executormocks.RemoteExecutor, scaleManager *bractionmocks.ScaleManager) {
				tidbCluster := &entity.TiDBCluster{
					Id:           "testclusterid",
					SharedPoolId: "testsharedpool",
					Phase:        apiv1.Cluster_AVAILABLE,
				}
				tidbGroups := []*entity.TiDBGroup{
					{
						TiDBGroup: apiv1.TiDBGroup{
							Id:    "testtidbgroup",
							Phase: apiv1.TiDBGroup_AVAILABLE,
						},
					},
				}

				tidbClusterRepo.On("Load", mock.Anything, "testclusterid", false).Return(tidbCluster, nil)
				tidbGroupRepo.On("List", mock.Anything, mock.Anything, mock.Anything, []string{"testclusterid"}, mock.Anything, false).Return(tidbGroups, nil)
				dagExecutor.On("QueryRunnings", mock.Anything, mock.Anything, mock.Anything).Return(nil, nil)
			},
			validate: func(t *testing.T, result *entity.TiDBCluster, err error) {
				t.Helper()
				require.NoError(t, err)
				require.NotNil(t, result)
				assert.Equal(t, "testclusterid", result.GetId())
				assert.Equal(t, apiv1.Cluster_AVAILABLE, result.GetPhase())
			},
		},
		{
			name:          "empty tidb cluster id",
			tidbClusterId: "",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, dagExecutor *executormocks.RemoteExecutor, scaleManager *bractionmocks.ScaleManager) {
				// No mocks needed for this test case
			},
			expectedError: "tidbClusterId is empty",
			expectedCode:  codes.InvalidArgument,
		},
		{
			name:          "tidb cluster not found in repo and dag",
			tidbClusterId: "non-existingcluster",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, dagExecutor *executormocks.RemoteExecutor, scaleManager *bractionmocks.ScaleManager) {
				tidbClusterRepo.On("Load", mock.Anything, "non-existingcluster", false).Return(nil, status.Error(codes.NotFound, "not found"))
			},
			expectedError: "tidbCluster non-existingcluster not found",
			expectedCode:  codes.NotFound,
		},
		{
			name:          "repo load error",
			tidbClusterId: "error-cluster",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, dagExecutor *executormocks.RemoteExecutor, scaleManager *bractionmocks.ScaleManager) {
				tidbClusterRepo.On("Load", mock.Anything, "error-cluster", false).Return(nil, status.Error(codes.Internal, "database error"))
			},
			expectedError: "failed to load tidbCluster:",
			expectedCode:  codes.Internal,
		},
		{
			name:          "topology driven without tidb worker should relax tiproxy health gate",
			tidbClusterId: "topology-cluster",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, dagExecutor *executormocks.RemoteExecutor, scaleManager *bractionmocks.ScaleManager) {
				tidbCluster := &entity.TiDBCluster{
					Id:           "topology-cluster",
					SharedPoolId: "sp-topology",
					Phase:        apiv1.Cluster_MODIFYING,
					CapacityMode: apiv1.CapacityMode_TOPOLOGY_DRIVEN,
				}

				sharedPool := &entity.SharedPool{
					SharedPool: apiv1.SharedPool{
						Id: "sp-topology",
						ComponentGroups: []*apiv1.Component{
							{ComponentType: apiv1.ComponentType_PD},
							{ComponentType: apiv1.ComponentType_TIKV},
							{ComponentType: apiv1.ComponentType_TIPROXY},
						},
					},
				}

				tidbClusterRepo.On("Load", mock.Anything, "topology-cluster", false).Return(tidbCluster, nil)
				sharedPoolRepo.On("Load", mock.Anything, "sp-topology", false).Return(sharedPool, nil)
				tidbGroupRepo.On("List", mock.Anything, mock.Anything, mock.Anything, []string{"topology-cluster"}, mock.Anything, false).Return([]*entity.TiDBGroup{}, nil)
				dagExecutor.On("QueryRunnings", mock.Anything, mock.Anything, mock.Anything).Return(nil, nil)
			},
			validate: func(t *testing.T, result *entity.TiDBCluster, err error) {
				t.Helper()
				require.NoError(t, err)
				require.NotNil(t, result)
				assert.Equal(t, apiv1.Cluster_AVAILABLE, result.GetPhase())
			},
		},
		{
			name:          "topology driven with tidb worker should keep tiproxy health gate",
			tidbClusterId: "topology-cluster-with-worker",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, dagExecutor *executormocks.RemoteExecutor, scaleManager *bractionmocks.ScaleManager) {
				tidbCluster := &entity.TiDBCluster{
					Id:           "topology-cluster-with-worker",
					SharedPoolId: "sp-topology-with-worker",
					Phase:        apiv1.Cluster_MODIFYING,
					CapacityMode: apiv1.CapacityMode_TOPOLOGY_DRIVEN,
				}

				sharedPool := &entity.SharedPool{
					SharedPool: apiv1.SharedPool{
						Id: "sp-topology-with-worker",
						ComponentGroups: []*apiv1.Component{
							{ComponentType: apiv1.ComponentType_PD},
							{ComponentType: apiv1.ComponentType_TIKV},
							{ComponentType: apiv1.ComponentType_TIDB_WORKER, NodeQuota: &apiv1.NodeQuota{NodeCount: 1}},
							{ComponentType: apiv1.ComponentType_TIPROXY},
						},
					},
				}

				tidbClusterRepo.On("Load", mock.Anything, "topology-cluster-with-worker", false).Return(tidbCluster, nil)
				sharedPoolRepo.On("Load", mock.Anything, "sp-topology-with-worker", false).Return(sharedPool, nil)
			},
			validate: func(t *testing.T, result *entity.TiDBCluster, err error) {
				t.Helper()
				require.NoError(t, err)
				require.NotNil(t, result)
				assert.Equal(t, apiv1.Cluster_MODIFYING, result.GetPhase())
			},
		},
		{
			name:          "topology driven with tidb worker node count zero should relax tiproxy health gate",
			tidbClusterId: "topology-cluster-with-zero-worker",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, dagExecutor *executormocks.RemoteExecutor, scaleManager *bractionmocks.ScaleManager) {
				tidbCluster := &entity.TiDBCluster{
					Id:           "topology-cluster-with-zero-worker",
					SharedPoolId: "sp-topology-with-zero-worker",
					Phase:        apiv1.Cluster_MODIFYING,
					CapacityMode: apiv1.CapacityMode_TOPOLOGY_DRIVEN,
				}

				sharedPool := &entity.SharedPool{
					SharedPool: apiv1.SharedPool{
						Id: "sp-topology-with-zero-worker",
						ComponentGroups: []*apiv1.Component{
							{ComponentType: apiv1.ComponentType_PD},
							{ComponentType: apiv1.ComponentType_TIKV},
							{ComponentType: apiv1.ComponentType_TIDB_WORKER, NodeQuota: &apiv1.NodeQuota{NodeCount: 0}},
							{ComponentType: apiv1.ComponentType_TIPROXY},
						},
					},
				}

				tidbClusterRepo.On("Load", mock.Anything, "topology-cluster-with-zero-worker", false).Return(tidbCluster, nil)
				sharedPoolRepo.On("Load", mock.Anything, "sp-topology-with-zero-worker", false).Return(sharedPool, nil)
				tidbGroupRepo.On("List", mock.Anything, mock.Anything, mock.Anything, []string{"topology-cluster-with-zero-worker"}, mock.Anything, false).Return([]*entity.TiDBGroup{}, nil)
				dagExecutor.On("QueryRunnings", mock.Anything, mock.Anything, mock.Anything).Return(nil, nil)
			},
			validate: func(t *testing.T, result *entity.TiDBCluster, err error) {
				t.Helper()
				require.NoError(t, err)
				require.NotNil(t, result)
				assert.Equal(t, apiv1.Cluster_AVAILABLE, result.GetPhase())
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Create mocks
			tidbClusterRepo := repomnocks.NewTiDBClusterRepo(t)
			sharedPoolRepo := repomnocks.NewSharedPoolRepo(t)
			tidbGroupRepo := repomnocks.NewTiDBGroupRepo(t)
			dagExecutor := executormocks.NewRemoteExecutor(t)
			scaleManager := bractionmocks.NewScaleManager(t)
			// Setup mocks
			tt.setupMocks(tidbClusterRepo, sharedPoolRepo, tidbGroupRepo, dagExecutor, scaleManager)

			// Create server implementation
			server := &serverImpl{
				tidbClusterRepo: tidbClusterRepo,
				sharedPoolRepo:  sharedPoolRepo,
				tidbGroupRepo:   tidbGroupRepo,
				dagExecutor:     dagExecutor,
				scaleManager:    scaleManager,
			}

			// Execute test
			result, err := server.GetTiDBCluster(context.Background(), tt.tidbClusterId)

			switch {
			case tt.expectedError != "":
				require.Error(t, err)
				assert.Contains(t, err.Error(), tt.expectedError)
				if tt.expectedCode != codes.OK {
					assert.Equal(t, tt.expectedCode, status.Code(err))
				}
				assert.Nil(t, result)

			case tt.validate != nil:
				tt.validate(t, result, err)

			default:
				require.NoError(t, err)
				require.NotNil(t, result)
			}
		})
	}
}
