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 DeleteSharedPoolMetaAction struct {
	clusterConfigClient clusterconfig.Client
}

const DeleteSharedPoolMetaName = "delete-shared-pool-meta"

func NewDeleteSharedPoolMetaAction(clusterConfigClient clusterconfig.Client) actions.Action {
	return &DeleteSharedPoolMetaAction{
		clusterConfigClient: clusterConfigClient,
	}
}

func (a *DeleteSharedPoolMetaAction) Name() string {
	return DeleteSharedPoolMetaName
}

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

	sharedPoolId, err := args.GetString(workflow.SharedPoolIdKey)
	if err != nil {
		return fmt.Errorf("failed to get shared pool id: %w", err)
	}

	err = a.clusterConfigClient.DeleteClusterMeta(ctx, sharedPoolId)
	if err != nil {
		tilog.Error(ctx, "failed to delete shared pool meta",
			zap.String("sharedPoolId", sharedPoolId),
			zap.Error(err),
		)
		return fmt.Errorf("failed to delete shared pool meta: %w", err)
	}

	return nil
}
