package testcase

import (
	"fmt"
	"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"
)

// CdcTikvRegionSplitSync
// create tidb cluster / mysql / workload
// create changefeed
// create database
// run workload
// modify region/key size to let region split
// finish mark synced to downstream.
// wait for workload finish
// check consistency
var _ = common.AddTestCase("cdc_tikv_region_split_sync", func() steps.Step {
	var (
		dbNameVar     = common.DBName
		changefeedID  = "kv-region-split-sync"
		loopLifeTime  = time.Hour
		loopCron      = 2 * time.Second
		prepareOption = common.Spec.GetWorkloadOption(workload.CommandTypePrepare)

		splitTables  []steps.Step
		splitStart   = 100
		splitRange   = 100000
		targetRegion = 20
	)

	for _, name := range prepareOption.GetTableNames() {
		query := fmt.Sprintf("SPLIT TABLE %s BETWEEN (%d) AND (%d) REGIONS %d", name, splitStart, splitStart+splitRange, targetRegion)
		splitTables = append(splitTables, steps.NewExecuteSQL(common.ResourceHandleSource, dbNameVar, query))
	}
	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).
		OperateChangeFeed(&ticdc.ChangeFeedCreateFlags{SinkType: ticdc.SinkTypeMySQL, ID: changefeedID}).
		Sleep(20*time.Second).
		CreateDatabase(common.ResourceHandleSource, dbNameVar).
		InitWorkload(common.ResourceHandleWorkload).
		RunWorkload(prepareOption).
		RunLoopTask(loopLifeTime, loopCron, false, splitTables...).
		Parallel(
			steps.NewKVFailureWithID(common.ResourceHandleSource, 0, 20*time.Minute),
			steps.NewRunWorkload(common.Spec.GetWorkloadOption(workload.CommandTypeRun)),
		).
		// UpdateConfig(resource.PD, "[schedule]\nmax-merge-region-keys = 20\nmax-merge-region-size = \"2MB\"", 10 * time.Minute).
		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()
})
