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

// OwnerSwitchSync
// create tidb cluster / mysql / workload
// create changefeed
// run workload
// Switch Owner: by pod failure chaos, duration as 15s, for duration as 5m, it will be canceled when finish mark synced to downstream.
// wait for workload finish
// check consistency
var _ = common.AddTestCase("owner_switch_sync", func() steps.Step {
	var (
		dbNameVar    = common.DBName
		changeFeedID = "owner-switch-sync"
	)
	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).
		InitCDCComponents(common.ResourceHandleSource, common.ResourceHandleMySQL).
		DropDatabasesIfExists(common.ResourceHandleSource, &dbNameVar).
		DropDatabasesIfExists(common.ResourceHandleMySQL, &dbNameVar).
		OperateChangeFeed(&ticdc.ChangeFeedCreateFlags{SinkType: ticdc.SinkTypeMySQL, ID: changeFeedID}).
		CreateDatabase(common.ResourceHandleSource, dbNameVar).
		InitWorkload(common.ResourceHandleWorkload).
		RunWorkload(common.Spec.GetWorkloadOption(workload.CommandTypePrepare)).
		Parallel(
			steps.NewPeriodicalTask(60*time.Minute, 5*time.Minute,
				steps.NewSwitchOwner(common.ResourceHandleSource, 20*time.Second)),

			steps.NewRunWorkload(common.Spec.GetWorkloadOption(workload.CommandTypeRun)),
		).
		SendFinishMark(dbNameVar).
		WaitFinishMark(common.ResourceHandleMySQL, dbNameVar, 5*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()
})
