package server

import (
	"context"
	"errors"
	"strings"
	"testing"

	apiv1 "github.com/tidbcloud/cluster-service-ng/api/cluster-service-ng/v1beta"
	"github.com/tidbcloud/cluster-service-ng/config"
	"github.com/tidbcloud/cluster-service-ng/domain/entity"
	"github.com/tidbcloud/cluster-service-ng/domain/server/br"
	"github.com/tidbcloud/cluster-service-ng/pkg/storage/mysql/schema"
	repomocks "github.com/tidbcloud/cluster-service-ng/pkg/storage/repo/mocks"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"gorm.io/gorm"
)

func TestServerImpl_GetLightweightRestore(t *testing.T) {
	tests := []struct {
		name           string
		req            *br.GetLightweightRestoreInput
		setupMocks     func(*repomocks.LightweightRestoreRepo)
		expectedOutput *br.GetLightweightRestoreOutput
		expectedError  error
		errorContains  string
		description    string
	}{
		{
			name: "restore not found",
			req: &br.GetLightweightRestoreInput{
				GetLightweightRestoreRequest: &apiv1.GetLightweightRestoreRequest{
					RestoreId: "restore-123",
				},
			},
			setupMocks: func(lwRestoreRepo *repomocks.LightweightRestoreRepo) {
				lwRestoreRepo.On("Load", context.Background(), "restore-123", true).Return(nil, status.Error(codes.NotFound, "restore not found"))
			},
			expectedOutput: nil,
			expectedError:  ErrLightweightRestoreNotFound,
			description:    "Should return ErrLightweightRestoreNotFound when restore record is not found",
		},
		{
			name: "database error while loading restore",
			req: &br.GetLightweightRestoreInput{
				GetLightweightRestoreRequest: &apiv1.GetLightweightRestoreRequest{
					RestoreId: "restore-123",
				},
			},
			setupMocks: func(lwRestoreRepo *repomocks.LightweightRestoreRepo) {
				lwRestoreRepo.On("Load", context.Background(), "restore-123", true).Return(nil, errors.New("database connection failed"))
			},
			expectedOutput: nil,
			expectedError:  nil, // We check error string instead
			errorContains:  "failed to load lw restore record",
			description:    "Should return wrapped error when database fails",
		},
		{
			name: "restore is deleted",
			req: &br.GetLightweightRestoreInput{
				GetLightweightRestoreRequest: &apiv1.GetLightweightRestoreRequest{
					RestoreId: "restore-123",
				},
			},
			setupMocks: func(lwRestoreRepo *repomocks.LightweightRestoreRepo) {
				// Mock deleted restore
				deletedRestore := &entity.LightweightRestore{
					LightweightRestore: schema.LightweightRestore{
						RestoreID: "restore-123",
					},
				}
				deletedRestore.DeletedAt = gorm.DeletedAt{Valid: true}
				lwRestoreRepo.On("Load", context.Background(), "restore-123", true).Return(deletedRestore, nil)
			},
			expectedOutput: &br.GetLightweightRestoreOutput{
				Status: apiv1.LightweightRestoreStatus_DELETED,
			},
			expectedError: nil,
			description:   "Should return DELETED status when restore is soft deleted",
		},
		{
			name: "restore status succeeded",
			req: &br.GetLightweightRestoreInput{
				GetLightweightRestoreRequest: &apiv1.GetLightweightRestoreRequest{
					RestoreId: "restore-123",
				},
			},
			setupMocks: func(lwRestoreRepo *repomocks.LightweightRestoreRepo) {
				// Mock succeeded restore
				succeededRestore := &entity.LightweightRestore{
					LightweightRestore: schema.LightweightRestore{
						RestoreID: "restore-123",
						Status:    schema.LightweightRestoreStatusSucceeded,
					},
				}
				lwRestoreRepo.On("Load", context.Background(), "restore-123", true).Return(succeededRestore, nil)
			},
			expectedOutput: &br.GetLightweightRestoreOutput{
				Status: apiv1.LightweightRestoreStatus_SUCCEED,
			},
			expectedError: nil,
			description:   "Should return SUCCEED status for succeeded restore",
		},
		{
			name: "restore status failed",
			req: &br.GetLightweightRestoreInput{
				GetLightweightRestoreRequest: &apiv1.GetLightweightRestoreRequest{
					RestoreId: "restore-123",
				},
			},
			setupMocks: func(lwRestoreRepo *repomocks.LightweightRestoreRepo) {
				// Mock failed restore
				failedRestore := &entity.LightweightRestore{
					LightweightRestore: schema.LightweightRestore{
						RestoreID:      "restore-123",
						Status:         schema.LightweightRestoreStatusFailed,
						FailureSource:  entity.RestoreFailureSourceKernel,
						FailureCode:    "KERNEL_TASK_FAILED",
						FailureMessage: "restore task error in kernel",
					},
				}
				lwRestoreRepo.On("Load", context.Background(), "restore-123", true).Return(failedRestore, nil)
			},
			expectedOutput: &br.GetLightweightRestoreOutput{
				Status: apiv1.LightweightRestoreStatus_FAILED,
				Failure: &apiv1.RestoreFailure{
					Source:  apiv1.RestoreFailureSource_KERNEL,
					Code:    "KERNEL_TASK_FAILED",
					Message: "restore task error in kernel",
				},
			},
			expectedError: nil,
			description:   "Should return FAILED status for failed restore",
		},
		{
			name: "restore status cancelled",
			req: &br.GetLightweightRestoreInput{
				GetLightweightRestoreRequest: &apiv1.GetLightweightRestoreRequest{
					RestoreId: "restore-123",
				},
			},
			setupMocks: func(lwRestoreRepo *repomocks.LightweightRestoreRepo) {
				// Mock cancelled restore
				cancelledRestore := &entity.LightweightRestore{
					LightweightRestore: schema.LightweightRestore{
						RestoreID: "restore-123",
						Status:    schema.LightweightRestoreStatusCancelled,
					},
				}
				lwRestoreRepo.On("Load", context.Background(), "restore-123", true).Return(cancelledRestore, nil)
			},
			expectedOutput: &br.GetLightweightRestoreOutput{
				Status: apiv1.LightweightRestoreStatus_DELETING,
			},
			expectedError: nil,
			description:   "Should return DELETING status for cancelled restore",
		},
		{
			name: "restore status unspecified/unknown",
			req: &br.GetLightweightRestoreInput{
				GetLightweightRestoreRequest: &apiv1.GetLightweightRestoreRequest{
					RestoreId: "restore-123",
				},
			},
			setupMocks: func(lwRestoreRepo *repomocks.LightweightRestoreRepo) {
				// Mock restore with unknown status
				unknownRestore := &entity.LightweightRestore{
					LightweightRestore: schema.LightweightRestore{
						RestoreID: "restore-123",
						Status:    "unknown_status", // Some status not handled in switch
					},
				}
				lwRestoreRepo.On("Load", context.Background(), "restore-123", true).Return(unknownRestore, nil)
			},
			expectedOutput: &br.GetLightweightRestoreOutput{
				Status: apiv1.LightweightRestoreStatus_LIGHTWEIGHT_RESTORE_STATUS_UNSPECIFIED,
			},
			expectedError: nil,
			description:   "Should return UNSPECIFIED status for unknown status",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Create mocks
			lwRestoreRepo := repomocks.NewLightweightRestoreRepo(t)

			// Setup mock expectations
			tt.setupMocks(lwRestoreRepo)

			// Create server
			server := &serverImpl{
				lwRestoreRepo: lwRestoreRepo,
				bizCfg: &config.BizConfig{
					DefaultTiBRConfig: config.TiBRConfig{
						StorageSize: "100Gi",
					},
				},
			}

			// Call the method
			ctx := context.Background()
			output, err := server.GetLightweightRestore(ctx, tt.req)

			// Check expectations
			if tt.expectedError != nil {
				if err == nil {
					t.Errorf("expected error %v but got none - %s", tt.expectedError, tt.description)
					return
				}
				if !errors.Is(err, tt.expectedError) {
					t.Errorf("expected error %v, got %v - %s", tt.expectedError, err, tt.description)
				}
				return
			}

			if tt.errorContains != "" {
				if err == nil {
					t.Errorf("expected error containing %q but got none - %s", tt.errorContains, tt.description)
					return
				}
				if !strings.Contains(err.Error(), tt.errorContains) {
					t.Errorf("expected error to contain %q, got %q - %s", tt.errorContains, err.Error(), tt.description)
				}
				return
			}

			if err != nil {
				// For the running status tests, we expect errors because we can't fully mock the adaptor factory
				if strings.Contains(tt.name, "restore status running") {
					// This is expected since we can't easily mock the adaptor without code changes
					t.Logf("Expected error for running status test due to adaptor implementation: %v", err)
					return
				}
				t.Errorf("unexpected error: %v - %s", err, tt.description)
				return
			}

			// Check output
			if tt.expectedOutput != nil {
				if output == nil {
					t.Errorf("expected output but got nil - %s", tt.description)
					return
				}
				if output.Status != tt.expectedOutput.Status {
					t.Errorf("expected status %v, got %v - %s", tt.expectedOutput.Status, output.Status, tt.description)
				}
				if tt.expectedOutput.Message != "" && output.Message != tt.expectedOutput.Message {
					t.Errorf("expected message %q, got %q - %s", tt.expectedOutput.Message, output.Message, tt.description)
				}
				if tt.expectedOutput.DataRestoreBytes != 0 && output.DataRestoreBytes != tt.expectedOutput.DataRestoreBytes {
					t.Errorf("expected bytes %v, got %v - %s", tt.expectedOutput.DataRestoreBytes, output.DataRestoreBytes, tt.description)
				}
			}
		})
	}
}
