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"
	"github.com/tidbcloud/cluster-service-ng/domain/workflow"
	brmocks "github.com/tidbcloud/cluster-service-ng/domain/workflow/action/br/mocks"
	"github.com/tidbcloud/cluster-service-ng/domain/workflow/dag"
	"github.com/tidbcloud/cluster-service-ng/pkg/runtime/actions"
	"github.com/tidbcloud/cluster-service-ng/pkg/runtime/executor"
	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"
	"google.golang.org/protobuf/encoding/protojson"
)

func TestGetTiDBGroup(t *testing.T) {
	tests := []struct {
		name          string
		tidbClusterId string
		tidbGroupId   string
		setupMocks    func(*repomnocks.TiDBClusterRepo, *repomnocks.TiDBGroupRepo, *repomnocks.SharedPoolRepo, *executormocks.RemoteExecutor)
		expectedError string
		expectedCode  codes.Code
		validate      func(*testing.T, *entity.TiDBGroup, error)
	}{
		{
			name:          "successful get existing tidb group",
			tidbClusterId: "testclusterid",
			tidbGroupId:   "testtidbgroup-id",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, dagExecutor *executormocks.RemoteExecutor) {
				tidbCluster := &entity.TiDBCluster{
					Id:           "testclusterid",
					SharedPoolId: "testsharedpool",
				}
				tidbGroup := &entity.TiDBGroup{
					TiDBGroup: apiv1.TiDBGroup{
						Id:           "testtidbgroup-id",
						ClusterId:    "testclusterid",
						SharedPoolId: "testsharedpool",
						Phase:        apiv1.TiDBGroup_AVAILABLE,
					},
				}

				tidbClusterRepo.On("Load", mock.Anything, "testclusterid", false).Return(tidbCluster, nil)
				tidbGroupRepo.On("Load", mock.Anything, "testtidbgroup-id", false).Return(tidbGroup, nil)
				dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanUpdateTiDBGroup, mock.Anything).Return(executor.ExecTaskIdStatus{}, nil)
				dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanDeleteTiDBGroup, mock.Anything).Return(executor.ExecTaskIdStatus{}, nil)
			},
			validate: func(t *testing.T, result *entity.TiDBGroup, err error) {
				t.Helper()
				require.NoError(t, err)
				require.NotNil(t, result)
				assert.Equal(t, "testtidbgroup-id", result.GetId())
				assert.Equal(t, "testclusterid", result.GetClusterId())
				assert.Equal(t, apiv1.TiDBGroup_AVAILABLE, result.GetPhase())
			},
		},
		{
			name:          "empty tidb cluster id",
			tidbClusterId: "",
			tidbGroupId:   "testtidbgroup-id",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, dagExecutor *executormocks.RemoteExecutor) {
				// No mocks needed for this test case
			},
			expectedError: "tidbClusterId is required",
			expectedCode:  codes.InvalidArgument,
		},
		{
			name:          "empty tidb group id",
			tidbClusterId: "testclusterid",
			tidbGroupId:   "",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, dagExecutor *executormocks.RemoteExecutor) {
				// No mocks needed for this test case
			},
			expectedError: "tidbGroupId is required",
			expectedCode:  codes.InvalidArgument,
		},
		{
			name:          "tidb cluster not found",
			tidbClusterId: "non-existingcluster",
			tidbGroupId:   "testtidbgroup-id",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, dagExecutor *executormocks.RemoteExecutor) {
				tidbClusterRepo.On("Load", mock.Anything, "non-existingcluster", false).Return(nil, status.Error(codes.NotFound, "not found"))
			},
			expectedError: "not found",
			expectedCode:  codes.NotFound,
		},
		{
			name:          "tidb cluster repo load error",
			tidbClusterId: "error-cluster",
			tidbGroupId:   "testtidbgroup-id",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, dagExecutor *executormocks.RemoteExecutor) {
				tidbClusterRepo.On("Load", mock.Anything, "error-cluster", false).Return(nil, status.Error(codes.Internal, "database error"))
			},
			expectedError: "database error",
			expectedCode:  codes.Internal,
		},
		{
			name:          "tidb group not found and not in creating",
			tidbClusterId: "testclusterid",
			tidbGroupId:   "nonexistinggroup",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, dagExecutor *executormocks.RemoteExecutor) {
				tidbCluster := &entity.TiDBCluster{
					Id:           "testclusterid",
					SharedPoolId: "testsharedpool",
				}

				tidbClusterRepo.On("Load", mock.Anything, "testclusterid", false).Return(tidbCluster, nil)
				tidbGroupRepo.On("Load", mock.Anything, "nonexistinggroup", false).Return(nil, status.Error(codes.NotFound, "not found"))
			},
			expectedError: "tidbGroup nonexistinggroup not found",
			expectedCode:  codes.NotFound,
		},
		{
			name:          "tidb group with running update dag",
			tidbClusterId: "testclusterid",
			tidbGroupId:   "updating-group",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, dagExecutor *executormocks.RemoteExecutor) {
				tidbCluster := &entity.TiDBCluster{
					Id:           "testclusterid",
					SharedPoolId: "testsharedpool",
				}
				tidbGroup := &entity.TiDBGroup{
					TiDBGroup: apiv1.TiDBGroup{
						Id:           "updating-group",
						ClusterId:    "testclusterid",
						SharedPoolId: "testsharedpool",
						Phase:        apiv1.TiDBGroup_AVAILABLE,
					},
				}
				updatedTidbGroup := &entity.TiDBGroup{
					TiDBGroup: apiv1.TiDBGroup{
						Id:           "updating-group",
						ClusterId:    "testclusterid",
						SharedPoolId: "testsharedpool",
						Phase:        apiv1.TiDBGroup_MODIFYING,
					},
				}

				tidbGroupStr, _ := protojson.Marshal(updatedTidbGroup)
				mockArgs := make(actions.ActionArgs)
				mockArgs[workflow.TiDBGroupKey] = actions.ActionArgString(string(tidbGroupStr))

				updateIns := executor.ExecTaskIdStatus{
					"exec-1": &executor.ExecTaskStatusEx{
						ExecTaskStatus: executor.ExecTaskStatus{
							ExecTask: &executor.ExecutorTask{
								Args: mockArgs,
							},
						},
					},
				}

				tidbClusterRepo.On("Load", mock.Anything, "testclusterid", false).Return(tidbCluster, nil)
				tidbGroupRepo.On("Load", mock.Anything, "updating-group", false).Return(tidbGroup, nil)
				dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanUpdateTiDBGroup, mock.Anything).Return(updateIns, nil)
				dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanDeleteTiDBGroup, mock.Anything).Return(executor.ExecTaskIdStatus{}, nil)
			},
			validate: func(t *testing.T, result *entity.TiDBGroup, err error) {
				t.Helper()
				require.NoError(t, err)
				require.NotNil(t, result)
				assert.Equal(t, "updating-group", result.GetId())
				assert.Equal(t, "testclusterid", result.GetClusterId())
				assert.Equal(t, apiv1.TiDBGroup_MODIFYING, result.GetPhase())
			},
		},
		{
			name:          "tidb group with running delete dag - not found",
			tidbClusterId: "testclusterid",
			tidbGroupId:   "deleting-group",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, dagExecutor *executormocks.RemoteExecutor) {
				tidbCluster := &entity.TiDBCluster{
					Id:           "testclusterid",
					SharedPoolId: "testsharedpool",
				}
				tidbGroup := &entity.TiDBGroup{
					TiDBGroup: apiv1.TiDBGroup{
						Id:           "deleting-group",
						ClusterId:    "testclusterid",
						SharedPoolId: "testsharedpool",
						Phase:        apiv1.TiDBGroup_AVAILABLE,
					},
				}

				deleteIns := executor.ExecTaskIdStatus{
					"exec-1": &executor.ExecTaskStatusEx{
						ExecTaskStatus: executor.ExecTaskStatus{
							ExecTask: &executor.ExecutorTask{
								Args: make(actions.ActionArgs),
							},
						},
					},
				}

				tidbClusterRepo.On("Load", mock.Anything, "testclusterid", false).Return(tidbCluster, nil)
				tidbGroupRepo.On("Load", mock.Anything, "deleting-group", false).Return(tidbGroup, nil)
				dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanUpdateTiDBGroup, mock.Anything).Return(executor.ExecTaskIdStatus{}, nil)
				dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanDeleteTiDBGroup, mock.Anything).Return(deleteIns, nil)
			},
			expectedError: "tidb group not found",
			expectedCode:  codes.NotFound,
		},
		{
			name:          "permission denied - tidb group belongs to different cluster",
			tidbClusterId: "testclusterid",
			tidbGroupId:   "other-cluster-group",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, dagExecutor *executormocks.RemoteExecutor) {
				tidbCluster := &entity.TiDBCluster{
					Id:           "testclusterid",
					SharedPoolId: "testsharedpool",
				}
				tidbGroup := &entity.TiDBGroup{
					TiDBGroup: apiv1.TiDBGroup{
						Id:        "other-cluster-group",
						ClusterId: "other-cluster-id", // Different cluster ID
						Phase:     apiv1.TiDBGroup_AVAILABLE,
					},
				}

				tidbClusterRepo.On("Load", mock.Anything, "testclusterid", false).Return(tidbCluster, nil)
				tidbGroupRepo.On("Load", mock.Anything, "other-cluster-group", false).Return(tidbGroup, nil)
				// No DAG calls expected because permission check fails early
			},
			expectedError: "tidb group other-cluster-group does not belong to tidb cluster testclusterid",
			expectedCode:  codes.PermissionDenied,
		},
		{
			name:          "error getting running update dag",
			tidbClusterId: "testclusterid",
			tidbGroupId:   "test-group",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, dagExecutor *executormocks.RemoteExecutor) {
				tidbCluster := &entity.TiDBCluster{
					Id:           "testclusterid",
					SharedPoolId: "testsharedpool",
				}
				tidbGroup := &entity.TiDBGroup{
					TiDBGroup: apiv1.TiDBGroup{
						Id:           "test-group",
						ClusterId:    "testclusterid",
						SharedPoolId: "testsharedpool",
						Phase:        apiv1.TiDBGroup_AVAILABLE,
					},
				}

				tidbClusterRepo.On("Load", mock.Anything, "testclusterid", false).Return(tidbCluster, nil)
				tidbGroupRepo.On("Load", mock.Anything, "test-group", false).Return(tidbGroup, nil)
				dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanUpdateTiDBGroup, mock.Anything).Return(nil, status.Error(codes.Internal, "dag executor error"))
			},
			expectedError: "failed to get running update tidb group dag instance:",
			expectedCode:  codes.Internal,
		},
		{
			name:          "error getting running delete dag",
			tidbClusterId: "testclusterid",
			tidbGroupId:   "test-group",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, dagExecutor *executormocks.RemoteExecutor) {
				tidbCluster := &entity.TiDBCluster{
					Id:           "testclusterid",
					SharedPoolId: "testsharedpool",
				}
				tidbGroup := &entity.TiDBGroup{
					TiDBGroup: apiv1.TiDBGroup{
						Id:           "test-group",
						ClusterId:    "testclusterid",
						SharedPoolId: "testsharedpool",
						Phase:        apiv1.TiDBGroup_AVAILABLE,
					},
				}

				tidbClusterRepo.On("Load", mock.Anything, "testclusterid", false).Return(tidbCluster, nil)
				tidbGroupRepo.On("Load", mock.Anything, "test-group", false).Return(tidbGroup, nil)
				dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanUpdateTiDBGroup, mock.Anything).Return(executor.ExecTaskIdStatus{}, nil)
				dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanDeleteTiDBGroup, mock.Anything).Return(nil, status.Error(codes.Internal, "dag executor error"))
			},
			expectedError: "failed to get running delete dag instance:",
			expectedCode:  codes.Internal,
		},
		{
			name:          "error unmarshaling tidb group from dag",
			tidbClusterId: "testclusterid",
			tidbGroupId:   "test-group",
			setupMocks: func(tidbClusterRepo *repomnocks.TiDBClusterRepo, tidbGroupRepo *repomnocks.TiDBGroupRepo, sharedPoolRepo *repomnocks.SharedPoolRepo, dagExecutor *executormocks.RemoteExecutor) {
				tidbCluster := &entity.TiDBCluster{
					Id:           "testclusterid",
					SharedPoolId: "testsharedpool",
				}
				tidbGroup := &entity.TiDBGroup{
					TiDBGroup: apiv1.TiDBGroup{
						Id:           "test-group",
						ClusterId:    "testclusterid", // Correct cluster ID
						SharedPoolId: "testsharedpool",
						Phase:        apiv1.TiDBGroup_AVAILABLE,
					},
				}

				// Invalid JSON for unmarshaling
				mockArgs := make(actions.ActionArgs)
				mockArgs[workflow.TiDBGroupKey] = actions.ActionArgString("invalid json")

				updateIns := executor.ExecTaskIdStatus{
					"exec-1": &executor.ExecTaskStatusEx{
						ExecTaskStatus: executor.ExecTaskStatus{
							ExecTask: &executor.ExecutorTask{
								Args: mockArgs,
							},
						},
					},
				}

				tidbClusterRepo.On("Load", mock.Anything, "testclusterid", false).Return(tidbCluster, nil)
				tidbGroupRepo.On("Load", mock.Anything, "test-group", false).Return(tidbGroup, nil)
				dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanUpdateTiDBGroup, mock.Anything).Return(updateIns, nil)
				// Don't mock delete DAG query since code returns error before reaching it
			},
			expectedError: "failed to unmarshal tidb group:",
			expectedCode:  codes.Internal,
			validate: func(t *testing.T, result *entity.TiDBGroup, err error) {
				t.Helper()
				require.Error(t, err)
				require.Nil(t, result)
				assert.Contains(t, err.Error(), "failed to unmarshal tidb group")
			},
		},
	}

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

			// Setup mocks
			tt.setupMocks(tidbClusterRepo, tidbGroupRepo, sharedPoolRepo, dagExecutor)

			// Default mocks for sharedPool and scaleManager (Maybe() allows them to not be called in early-fail test cases)
			sharedPool := &entity.SharedPool{
				SharedPool: apiv1.SharedPool{
					Id:    "testsharedpool",
					Phase: apiv1.SharedPool_AVAILABLE,
				},
			}
			sharedPoolRepo.On("Load", mock.Anything, mock.Anything, false).Maybe().Return(sharedPool, nil)
			scaleManager.On("AnyFullfillingDecision", mock.Anything, mock.Anything).Maybe().Return(false, nil)

			// Setup default mocks for SharedPool DAG queries (always needed when sharedPool is loaded)
			// These use Maybe() to allow early-return test cases to skip them
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanCreateSharedPool, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanDeleteSharedPool, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanPauseSharedPool, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanResumeSharedPool, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanUpdateComponent, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanApplyComponent, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanCreateComponent, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanDeleteTiKVGroup, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanSetSharedPoolPDDeploymentModeToMonolithic, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanSetSharedPoolPDDeploymentModeToMicroservice, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanCreateTiDBCluster, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanUpdateTiDBCluster, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanDeleteTiDBCluster, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanCreateTiDBGroup, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanUpdateTiDBGroup, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)
			dagExecutor.On("QueryRunnings", mock.Anything, dag.PlanDeleteTiDBGroup, mock.AnythingOfType("executor.MatchFilter")).Maybe().Return(executor.ExecTaskIdStatus{}, nil)

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

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

			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)
			}
		})
	}
}
