package subscriber

import (
	"context"
	"errors"
	"testing"

	"github.com/stretchr/testify/require"
	core_event "github.com/tidbcloud/core-svc/event"
	"github.com/tidbcloud/pkgv2/db/mock_db"
	"github.com/tidbcloud/serverless-service/internal/domain/repo/mock_repo"
	"github.com/tidbcloud/serverless-service/internal/service/event_svc"
	"go.uber.org/mock/gomock"
)

func TestBackupClusterEventHandlerRunsLegacyDeletionWhenVirtualizedDeletionFails(t *testing.T) {
	ctrl := gomock.NewController(t)
	dbProvider := mock_db.NewMockTransProvider(ctrl)
	backupSchedule := mock_repo.NewMockBackupScheduleRepo(ctrl)
	virtualizedErr := errors.New("virtualized backup history unavailable")

	dbProvider.EXPECT().Transaction(gomock.Any(), gomock.Any()).Return(virtualizedErr)
	backupSchedule.EXPECT().DeleteByClusterID(gomock.Any(), "1").Return(nil)
	handler := NewBackupClusterEventHandler(
		event_svc.NewBackupEventService(backupSchedule, nil, nil, nil),
		event_svc.NewVirtualizedBackupEventService(nil, nil, dbProvider),
	)

	err := handler.Handle(context.Background(), &core_event.ClusterEvent{
		ClusterID: 1,
		IsDevTier: true,
		EventType: core_event.ClusterEventTypeDeleted,
	})
	require.ErrorIs(t, err, virtualizedErr)
}
