package workflows

import (
	"fmt"

	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	"github.com/tidbcloud/infra-provider/pkg/consts"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func NewDisableTiProxy(cluster *cloudv1.Cluster, groupID, wfNameSuffix string) *cloudv1.Workflow {
	wf := &cloudv1.Workflow{
		ObjectMeta: metav1.ObjectMeta{
			Namespace: cluster.Namespace,
			Name:      fmt.Sprintf("%s-%s", consts.WorkflowTypeDisableTiProxy, wfNameSuffix),
			Labels:    buildLabels(consts.WorkflowTypeDisableTiProxy, cluster, groupID),
		},
		Spec: cloudv1.WorkflowSpec{
			Type: consts.WorkflowTypeDisableTiProxy,
			TTL:  defaultTTL,
			Steps: cloudv1.WorkflowSteps{
				{
					Name: "Use TiDB as LB target",
					Uses: consts.WorkflowActionToggleLBTarget,
					Inputs: cloudv1.InputsWrapper{
						Object: map[string]interface{}{
							"name":       cluster.Name,
							"namespace":  cluster.Namespace,
							"groupId":    groupID,
							"useTiProxy": false,
						},
					},
				},
				// TODO(ideascf): check k8s service to ensure the LB target is on TiDB.
				{
					Name: "Wait for LB switching to complete",
					Uses: consts.WorkflowActionSleep,
					Inputs: cloudv1.InputsWrapper{
						Object: map[string]interface{}{
							"duration": getWaitTimeToggleLBTarget(cluster),
						},
					},
				},
				{
					Name: "Mark LB target on TiDB",
					Uses: consts.WorkflowActionMutateAnnotations,
					Inputs: cloudv1.InputsWrapper{
						Object: map[string]interface{}{
							"name":      cluster.Name,
							"namespace": cluster.Namespace,
							"type":      "cluster",
							"annotations": map[string]string{
								consts.AnnoKeyLBTargetOnTiProxy(groupID): "-",
							},
						},
					},
				},
				{
					Name: "Remove TiProxy",
					Uses: consts.WorkflowActionRemoveTiProxy,
					Inputs: cloudv1.InputsWrapper{
						Object: map[string]interface{}{
							"name":      cluster.Name,
							"namespace": cluster.Namespace,
							"groupId":   groupID,
						},
					},
				},
				{
					Name: "Mark LB toggle finished",
					Uses: consts.WorkflowActionMutateAnnotations,
					Inputs: cloudv1.InputsWrapper{
						Object: map[string]interface{}{
							"name":      cluster.Name,
							"namespace": cluster.Namespace,
							"type":      "cluster",
							"annotations": map[string]string{
								consts.AnnoKeyTiProxyToggleWorkflow: "-",
							},
						},
					},
				},
			},
		},
	}

	return wf
}
