package tcaction

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	opent "github.com/tidbcloud/devops/entity/operation"
	"github.com/tidbcloud/devops/pkg/service/operation/actions"

	apiv1 "github.com/tidbcloud/infra-provider/api/tidbcloud/cluster-agent/v1"
)

var (
	ActionResumeTC opent.ActionMetadata = opent.ActionMetadata{
		Name: "ResumeTC",
		Type: opent.ActionTypeAuto,
	}
)

type resumeCluster struct {
	actions.BaseAction
	comps *actions.Components
}

func NewResumeTC(comps *actions.Components) actions.AutoAction {
	return &resumeCluster{comps: comps}
}

func (a *resumeCluster) Metadata() opent.ActionMetadata {
	return ActionResumeTC
}

func (a *resumeCluster) PreCheck(ctx context.Context, instance *opent.Instance) error {
	cid, err := actions.GetClusterID(instance)
	if err != nil {
		return err
	}

	_, err = a.comps.CoreSvc.GetCluster(ctx, cid, false)
	return err
}

func (a *resumeCluster) Start(ctx context.Context, instance *opent.Instance) (*actions.ActionResult, error) {
	req, err := a.getParam(instance)
	if err != nil {
		return actions.FailedActionResult(err), nil
	}

	resp, err := a.comps.MgmtHTTP.ClusterAgent(req.ClusterId).ResumeTC(ctx, req)
	if err != nil {
		return nil, err
	}

	output := map[opent.OutputName]string{
		opent.OutputResumedTCNames: strings.Join(resp.ResumedTcNames, ", "),
	}
	return actions.RunningActionResult("sent request to resume TC(s)", output), nil
}

func (a *resumeCluster) Result(ctx context.Context, instance *opent.Instance) (*actions.ActionResult, error) {
	param, err := a.getParam(instance)
	if err != nil {
		return nil, err
	}

	tcs, err := a.comps.MgmtHTTP.ClusterAgent(param.ClusterId).ListTCs(ctx)
	if err != nil {
		return actions.NewActionResult(opent.ActionStatusUnknown, err.Error(), nil), nil
	}

	var unresumedTCs []string
	for _, each := range tcs {
		if each.Paused {
			unresumedTCs = append(unresumedTCs, each.K8SMetadata.Name)
		}
	}
	if len(unresumedTCs) != 0 {
		return actions.RunningActionResult(fmt.Sprintf("unresumed tcs: %v", unresumedTCs), nil), nil
	}

	return actions.SucceededActionResult(nil), nil
}

func (a *resumeCluster) getParam(instance *opent.Instance) (*apiv1.ResumeTCReq, error) {
	cid, err := actions.GetClusterID(instance)
	if err != nil {
		return nil, err
	}

	p := &apiv1.ResumeTCReq{
		ClusterId: strconv.FormatUint(cid, 10),
		All:       true,
		TcNames:   nil,
	}
	return p, nil
}
