package action

import (
	"fmt"

	"github.com/tidbcloud/cluster-service-ng/domain/workflow"
	"github.com/tidbcloud/cluster-service-ng/pkg/clusterconfig"
	"github.com/tidbcloud/cluster-service-ng/pkg/runtime/actions"
	"github.com/tidbcloud/cluster-service-ng/pkg/utils"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
)

type DeleteTiDBClusterMetaAction struct {
	clusterConfigClient clusterconfig.Client
}

const DeleteTiDBClusterMetaName = "delete-tidb-cluster-meta"

func NewDeleteTiDBClusterMetaAction(clusterConfigClient clusterconfig.Client) actions.Action {
	return &DeleteTiDBClusterMetaAction{
		clusterConfigClient: clusterConfigClient,
	}
}

func (a *DeleteTiDBClusterMetaAction) Name() string {
	return DeleteTiDBClusterMetaName
}

func (a *DeleteTiDBClusterMetaAction) Invoke(args actions.ActionArgs) error {
	ctx := utils.GenerateContext(args)
	tilog.Info(ctx, "delete tidb cluster meta action invoked")

	tidbClusterId, err := args.GetString(workflow.TiDBClusterIdKey)
	if err != nil {
		return fmt.Errorf("failed to get tidb cluster id: %w", err)
	}

	err = a.clusterConfigClient.DeleteTiDBClusterMeta(ctx, tidbClusterId)
	if err != nil {
		tilog.Error(ctx, "failed to delete tidb cluster meta",
			zap.String("tidbClusterId", tidbClusterId),
			zap.Error(err),
		)
		return fmt.Errorf("failed to delete tidb cluster meta: %w", err)
	}

	return nil
}
