package dm

import (
	"fmt"
	"time"

	. "github.com/tidbcloud/dataflow-service-e2e/cases"
	"github.com/tidbcloud/dataflow-service-e2e/cases/dedicated/common"
	"github.com/tidbcloud/dataflow-service-e2e/internal/config"
	. "github.com/tidbcloud/dataflow-service-e2e/internal/model"
	"github.com/tidbcloud/dataflow-service-e2e/internal/tidbcloud/dedicated/consoleapi"
	dm_model "github.com/tidbcloud/dataflow-service-e2e/internal/tidbcloud/dedicated/consoleapi/dm/model"
)

// dmIncrementalMigrationSmokeCase tests incremental migration (binlog sync) for a DM job.
// It covers:
// - Create an incremental-mode DM job
// - Wait for job to start running (syncing binlog)
// - Verify job stays in Running state (continuous sync)
// - Pause the job
// - Resume the job
// - Delete the job
type dmIncrementalMigrationSmokeCase struct {
	BaseCase
	dmValidator   *common.DMValidator
	cloudProvider CloudProviderType
}

// NewDMIncrementalMigrationSmokeCase creates a new incremental migration smoke test case.
func NewDMIncrementalMigrationSmokeCase(cloudProvider CloudProviderType) E2ECase {
	return &dmIncrementalMigrationSmokeCase{cloudProvider: cloudProvider}
}

func (m *dmIncrementalMigrationSmokeCase) Name() string {
	return fmt.Sprintf("%sDMIncrementalMigrationSmoke", m.cloudProvider)
}

func (m *dmIncrementalMigrationSmokeCase) Tags() map[string]string {
	return map[string]string{TagKeyDomain: TagValueDomainDM}
}

func (m *dmIncrementalMigrationSmokeCase) DeclareDependencyRequirements() map[string]DependencyRequirement {
	return map[string]DependencyRequirement{
		"tidb": &TiDBDedicatedRequirement{
			Dedicated: false,
			TiDBDedicatedDimensions: TiDBDedicatedDimensions{
				CloudProvider: m.cloudProvider,
				Region:        config.GlobalConfig.DefaultRegionOf(m.cloudProvider),
			},
		},
		"mysql": &MySQLRequirement{
			MySQLDimensions: MySQLDimensions{
				NetworkType: DataflowNetworkTypeNetworkTypePublic,
			},
		},
	}
}

func (m *dmIncrementalMigrationSmokeCase) Run() {
	tidbCluster := m.TiDBDedicated("tidb")
	mysql := m.MySQL("mysql")
	m.dmValidator = common.NewDMValidator(m.Logger())

	var jobID string
	var specID string
	var connProfileID string
	var precheckID string

	// Cleanup: delete the created DM job
	defer func() {
		if jobID != "" {
			m.RetryDo(fmt.Sprintf("cleanup: delete DM job %s", jobID), func() error {
				return m.dmValidator.Client().DeleteJob(tidbCluster, jobID)
			}, DefaultRetryAttempts, DefaultRetryInterval)
		}
	}()

	m.
		// Step 1: Get available DM job spec
		Step("get DM job spec", func() error {
			spec, err := m.dmValidator.GetFirstJobSpec()
			if err != nil {
				return err
			}
			specID = spec.ID
			return nil
		}).

		// Step 2: Register connection profile for the MySQL source
		Step("create conn profile", func() error {
			id, err := consoleapi.NewConnProfileClientWrapper(m.Logger()).CreateConnProfile(
				tidbCluster, mysql, GenerateDMJobName("cp"),
			)
			if err != nil {
				return err
			}
			connProfileID = id
			return nil
		}).

		// Step 3: Submit precheck
		Step("submit DM precheck", func() error {
			body := BuildPrecheckBody(
				GenerateDMJobName("pc"), DMModeIncremental, DMImportModeLogical, specID,
				tidbCluster, mysql, false,
			)
			id, err := m.dmValidator.Client().PrecheckJob(tidbCluster, body)
			if err != nil {
				return err
			}
			precheckID = id
			m.Logger().Info("precheck submitted: %s", precheckID)
			return nil
		}).

		// Step 4: Wait for precheck to complete
		Expect("precheck is done", func() error {
			return m.dmValidator.IsPrecheckDone(tidbCluster, precheckID)
		}, uint(PrecheckTimeout/(30*time.Second)), 30*time.Second).

		// Step 5: Create an incremental-mode DM job
		Step("create incremental-mode DM job", func() error {
			jobName := GenerateDMJobName("incr")
			body := BuildCreateJobBody(
				jobName, DMModeIncremental, DMImportModeLogical, specID,
				tidbCluster, connProfileID, precheckID, false, []string{DefaultDBForDMTest},
			)
			resp, err := m.dmValidator.Client().CreateJob(tidbCluster, body)
			if err != nil {
				return err
			}
			jobID = resp.Payload.ID
			m.Logger().Info("created incremental DM job: %s", jobID)
			return nil
		}).

		// Step 6: Wait for job to start running
		Expect("DM job is running", func() error {
			return m.dmValidator.IsJobRunning(tidbCluster, jobID)
		}, DefaultExpectAttempts, DefaultExpectInterval).

		// Step 7: Verify job stays running (incremental sync is continuous)
		Still("DM job remains running", func() error {
			return m.dmValidator.IsJobRunning(tidbCluster, jobID)
		}, 3, time.Minute).

		// Step 8: Pause the job
		Step("pause DM job", func() error {
			return m.dmValidator.Client().OperateJob(tidbCluster, jobID, dm_model.DmOperateJobReqOperationPause)
		}).

		// Step 9: Wait for job to be paused
		Expect("DM job is paused", func() error {
			return m.dmValidator.IsJobPaused(tidbCluster, jobID)
		}, 20, DefaultExpectInterval).

		// Step 10: Resume the job
		Step("resume DM job", func() error {
			return m.dmValidator.Client().OperateJob(tidbCluster, jobID, dm_model.DmOperateJobReqOperationResume)
		}).

		// Step 11: Wait for job to be running again
		Expect("DM job is running again", func() error {
			return m.dmValidator.IsJobRunning(tidbCluster, jobID)
		}, DefaultExpectAttempts, DefaultExpectInterval).

		// Step 12: Delete the job
		RetryDo("delete DM job", func() error {
			return m.dmValidator.Client().DeleteJob(tidbCluster, jobID)
		}, DefaultRetryAttempts, DefaultRetryInterval).

		// Step 13: Verify job is deleted
		Expect("DM job is deleted", func() error {
			return m.dmValidator.IsJobDeleted(tidbCluster, jobID)
		}, 10, 30*time.Second)

	jobID = ""
}
