package action

import (
	"fmt"

	"github.com/tidbcloud/cluster-service-ng/domain/workflow"
	"github.com/tidbcloud/cluster-service-ng/pkg/k8s"
	"github.com/tidbcloud/cluster-service-ng/pkg/runtime/actions"
	"github.com/tidbcloud/cluster-service-ng/pkg/utils"
	o11yv2 "github.com/tidbcloud/observability/agent-control-server/api/v2"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

const (
	DeleteO11ySharedPoolAgentActionName = "delete-o11y-sharedpool-agent"
)

type DeleteO11ySharedPoolAgentAction struct {
	disableO11y    bool
	kubeClient     client.Client
	agentNamespace string
}

func NewDeleteO11ySharedPoolAgentAction(
	disableO11y bool,
	kubeClient client.Client,
	agentNamespace ...string,
) *DeleteO11ySharedPoolAgentAction {
	return &DeleteO11ySharedPoolAgentAction{
		disableO11y:    disableO11y,
		kubeClient:     kubeClient,
		agentNamespace: resolveO11yAgentNamespace(agentNamespace...),
	}
}

func (a *DeleteO11ySharedPoolAgentAction) Name() string {
	return DeleteO11ySharedPoolAgentActionName
}

// we do not check o11y agent status since it is not a core step
func (a *DeleteO11ySharedPoolAgentAction) Invoke(args actions.ActionArgs) error {
	ctx := utils.GenerateContext(args)
	if a.disableO11y {
		tilog.Info(ctx, "o11y is disabled, skip delete o11y sharedpool agent")
		return nil
	}
	tilog.Info(ctx, "delete o11y sharedpool agent action invoked")
	sharedPoolId, err := args.GetString(workflow.SharedPoolIdKey)
	if err != nil {
		return fmt.Errorf("failed to get sharedpool id: %w", err)
	}
	agent := new(o11yv2.SharedPoolAgent)
	agent.Name = sharedPoolId
	agent.Namespace = a.agentNamespace

	if err := k8s.DeleteObject(ctx, a.kubeClient, agent); err != nil {
		tilog.Error(ctx, "failed to delete o11y sharedpool agent", zap.Error(err))
		return err
	}
	return nil
}
