package changefeed

import (
	"fmt"

	"github.com/shiningrush/fastflow/pkg/entity"
	"github.com/shiningrush/fastflow/pkg/entity/run"
	appworkflow "github.com/tidbcloud/serverless-service/internal/workflow"
	workflowchangefeed "github.com/tidbcloud/serverless-service/internal/workflow/action/changefeed"
	"github.com/tidbcloud/serverless-service/internal/workflow/action/changefeed/create"
)

func GetCreateChangefeedDag(hook appworkflow.CDCNewArchHook) (*entity.Dag, []run.Action) {
	scheduler := workflowchangefeed.NewSharedScheduler(hook)
	actions := []run.Action{
		create.NewRegisterClusterJobAction(hook),
		create.NewCreateOrScaleClusterAction(scheduler),
		create.NewCreateChangefeedAction(hook),
		create.NewFinalAction(hook),
	}

	dag := &entity.Dag{
		BaseInfo: entity.BaseInfo{
			ID: appworkflow.DagCreateNewArchChangefeed,
		},
		Name: appworkflow.DagCreateNewArchChangefeed,
		Vars: entity.DagVars{
			"cluster_id":    {},
			"changefeed_id": {},
		},
		Status: entity.DagStatusNormal,
		Tasks: []entity.Task{
			{
				ID:         appworkflow.ActionRegisterClusterJob,
				ActionName: appworkflow.ActionRegisterClusterJob,
				Params: map[string]any{
					"cluster_id":    fmt.Sprintf("{{%s}}", "cluster_id"),
					"changefeed_id": fmt.Sprintf("{{%s}}", "changefeed_id"),
				},
				TimeoutSecs: 3 * 60,
			},
			{
				ID:         appworkflow.ActionCreateOrScaleNewArchCluster,
				ActionName: appworkflow.ActionCreateOrScaleNewArchCluster,
				Params: map[string]any{
					"cluster_id":    fmt.Sprintf("{{%s}}", "cluster_id"),
					"changefeed_id": fmt.Sprintf("{{%s}}", "changefeed_id"),
				},
				TimeoutSecs: 60 * 60,
				DependOn:    []string{appworkflow.ActionRegisterClusterJob},
			},
			{
				ID:         appworkflow.ActionCreateNewArchFeed,
				ActionName: appworkflow.ActionCreateNewArchFeed,
				Params: map[string]any{
					"cluster_id":    fmt.Sprintf("{{%s}}", "cluster_id"),
					"changefeed_id": fmt.Sprintf("{{%s}}", "changefeed_id"),
				},
				TimeoutSecs: 10 * 60,
				DependOn:    []string{appworkflow.ActionCreateOrScaleNewArchCluster},
			},
			{
				ID:         appworkflow.ActionCreateNewArchFinal,
				ActionName: appworkflow.ActionCreateNewArchFinal,
				Params: map[string]any{
					"cluster_id":    fmt.Sprintf("{{%s}}", "cluster_id"),
					"changefeed_id": fmt.Sprintf("{{%s}}", "changefeed_id"),
				},
				TimeoutSecs: 3 * 60,
				DependOn:    []string{appworkflow.ActionCreateNewArchFeed},
			},
		},
	}
	return dag, actions
}
