package action

import (
	"fmt"

	apiv1 "github.com/tidbcloud/cluster-service-ng/api/cluster-service-ng/v1beta"
	"github.com/tidbcloud/cluster-service-ng/domain/entity"
	"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"
)

const DeleteTiKVComponentConfigActionName = "delete-tikv-component-config"

type DeleteTiKVComponentConfigAction struct {
	clusterConfigClient clusterconfig.Client
}

func NewDeleteTiKVComponentConfigAction(clusterConfigClient clusterconfig.Client) actions.Action {
	return &DeleteTiKVComponentConfigAction{
		clusterConfigClient: clusterConfigClient,
	}
}

func (a *DeleteTiKVComponentConfigAction) Name() string {
	return DeleteTiKVComponentConfigActionName
}

func (a *DeleteTiKVComponentConfigAction) Invoke(args actions.ActionArgs) error {
	ctx := utils.GenerateContext(args)
	tilog.Info(ctx, "delete tikv component config action invoked")

	sharedPool, err := deleteComponentTargetSharedPool(args)
	if err != nil {
		return err
	}

	for _, comp := range sharedPool.GetComponentGroups() {
		if comp.GetPhase() != apiv1.Component_DELETING || !workflow.CheckIsTargetComponent(ctx, comp, args) {
			continue
		}
		if comp.GetComponentType() != apiv1.ComponentType_TIKV {
			tilog.Info(ctx, "component config delete is not supported for component type, skip",
				zap.String("componentId", comp.GetId()),
				zap.String("componentType", entity.GetComponentTypeName(comp)))
			continue
		}
		if err := a.clusterConfigClient.DeleteTiKVComponentConfig(ctx, sharedPool, comp); err != nil {
			return fmt.Errorf("failed to delete tikv component config for %s: %w", comp.GetId(), err)
		}
	}
	return nil
}
