package testcase

import (
	"time"

	"github.com/pingcap/test-infra/caselib/pkg/model/ticdc"
	"github.com/pingcap/test-infra/caselib/pkg/model/workload"
	"github.com/pingcap/test-infra/caselib/pkg/steps"
	"github.com/pingcap/test-infra/caselib/ticdc/common"
	"github.com/pingcap/tiflow/cdc/model"
)

// All cdc,pd, tikv restart by pod failure
// create tidb cluster / mysql / workload
// create changefeed
// create database
// prepare workload, make all pd failed/restart: by pod failure chaos
// run workload, make all captures failed/restart: by pod failure chaos
// make all tikv component failed/restart: by pod failure chaos, duration as 1m, it will be canceled when finish mark synced to downstream.
// wait for workload finish
// check consistency
var _ = common.AddTestCase("cdc_all_node_restart_sync", func() steps.Step {
	var (
		changeFeedID = "cdc-all-node-restart-sync"
		dbNameVar    = common.DBName
	)
	return steps.
		NewBuilder().
		LoadEnv().
		LoadResourceFromEnv("TI_PARAM_RES_upstream", common.ResourceHandleSource).
		LoadResourceFromEnv("TI_PARAM_RES_downstream", common.ResourceHandleMySQL).
		LoadResourceFromEnv("TI_PARAM_RES_workload", common.ResourceHandleWorkload).
		// EnableTiDBGeneralLog(resourceHandleSource).
		InitCDCComponents(common.ResourceHandleSource, common.ResourceHandleMySQL).
		OperateChangeFeed(&ticdc.ChangeFeedCreateFlags{SinkType: ticdc.SinkTypeMySQL, ID: changeFeedID}).
		CreateDatabase(common.ResourceHandleSource, dbNameVar).
		InitWorkload(common.ResourceHandleWorkload).
		Parallel(
			steps.NewRunWorkload(common.Spec.GetWorkloadOption(workload.CommandTypePrepare)),
			steps.NewAllPDRestart(common.ResourceHandleSource, 20*time.Second),
		).
		Parallel(
			steps.NewAllCaptureRestart(common.ResourceHandleSource, 20*time.Second),
			steps.NewRunWorkload(common.Spec.GetWorkloadOption(workload.CommandTypeRun)),
		).
		MakeTiKVFailure(common.ResourceHandleSource, time.Minute).
		SendFinishMark(dbNameVar).
		WaitFinishMark(common.ResourceHandleMySQL, dbNameVar, 3*time.Hour).
		CheckConsistency(common.ResourceHandleSource, common.ResourceHandleMySQL, dbNameVar).
		DropDatabasesIfExists(common.ResourceHandleSource, &dbNameVar).
		Sleep(1 * time.Minute).
		OperateChangeFeed(&ticdc.ChangeFeedAdminJobFlags{JobType: model.AdminRemove, ID: changeFeedID, ForceRemove: true}).
		Build()
})
