package action

import (
	"github.com/tidbcloud/fastflow/pkg/entity/run"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"

	"github.com/tidbcloud/tidb-management-service/dedicated-global-service/domain/adapter/clusterconfig"
	clusterrepo "github.com/tidbcloud/tidb-management-service/dedicated-global-service/domain/repository/cluster"
	"github.com/tidbcloud/tidb-management-service/dedicated-global-service/domain/service/workflow/common"
	"github.com/tidbcloud/tidb-management-service/utilities/workflow"
)

const (
	DeleteClusterMeta = "delete_cluster_meta"
)

type DeleteClusterMetaAction struct {
	clusterRepo      clusterrepo.Repo
	clusterConfigCli clusterconfig.Client
}

func NewDeleteClusterMetaAction(
	clusterRepo clusterrepo.Repo,
	clusterConfigCli clusterconfig.Client,
) *DeleteClusterMetaAction {
	return &DeleteClusterMetaAction{
		clusterRepo:      clusterRepo,
		clusterConfigCli: clusterConfigCli,
	}
}

func (a *DeleteClusterMetaAction) Name() string {
	return DeleteClusterMeta
}

func (a *DeleteClusterMetaAction) ParameterNew() any {
	return &common.ClusterIdParameter{}
}

func (a *DeleteClusterMetaAction) Run(ctx run.ExecuteContext, params any) error {
	cctx, span := workflow.GenerateContext(ctx)

	clusterId, err := common.GetClusterId(params)
	if err != nil {
		tilog.Error(cctx, "failed to get cluster id", zap.Error(err))
		return err
	}

	tilog.Info(cctx, "start to delete cluster meta", zap.Uint64("cluster_id", clusterId))
	defer func() {
		tilog.Info(cctx, "end to delete cluster meta", zap.Uint64("cluster_id", clusterId))
		span.End()
	}()

	cluster, err := a.clusterRepo.Get(cctx, clusterId, true)
	if err != nil {
		tilog.Error(cctx, "failed to get cluster", zap.Uint64("cluster_id", clusterId), zap.Error(err))
		return err
	}

	if err := a.clusterConfigCli.DeleteClusterMeta(cctx, cluster); err != nil {
		tilog.Error(cctx, "failed to delete cluster meta", zap.Uint64("cluster_id", clusterId), zap.Error(err))
		return err
	}

	return nil
}
