package ngoperation

import (
	"context"
	"fmt"
	"strconv"

	opent "github.com/tidbcloud/devops/entity/operation"
	"github.com/tidbcloud/devops/pkg/service/operation/actions"
)

var (
	ActionDeleteChangefeedVPCPeering opent.ActionMetadata = opent.ActionMetadata{
		Name: "DeleteChangefeedVPCPeering",
		Type: opent.ActionTypeAuto,
	}
)

type deleteChangefeedVPCPeering struct {
	actions.BaseAction
	comps *actions.Components
}

func NewDeleteChangefeedVPCPeering(comps *actions.Components) actions.AutoAction {
	return &deleteChangefeedVPCPeering{
		comps: comps,
	}
}

func (p *deleteChangefeedVPCPeering) Metadata() opent.ActionMetadata {
	return ActionDeleteChangefeedVPCPeering
}

func (p *deleteChangefeedVPCPeering) PreCheck(ctx context.Context, instance *opent.Instance) error {
	_, _, _, err := p.getParam(ctx, instance)
	if err != nil {
		return err
	}

	return nil
}

func (p *deleteChangefeedVPCPeering) Start(ctx context.Context, instance *opent.Instance) (*actions.ActionResult, error) {
	cid, dataPlaneID, vpcPeeringID, err := p.getParam(ctx, instance)
	if err != nil {
		return actions.FailedActionResult(err), nil
	}
	err = p.comps.MgmtHTTP.NextGen().DeleteVPCPeering(ctx, cid, dataPlaneID, vpcPeeringID)
	if err != nil {
		return actions.FailedActionResult(err), nil
	}

	return actions.SucceededActionResult(nil), nil // return succeeded directly
}

func (p *deleteChangefeedVPCPeering) Result(ctx context.Context, instance *opent.Instance) (*actions.ActionResult, error) {
	return actions.SucceededActionResult(nil), nil
}

func (p *deleteChangefeedVPCPeering) getParam(ctx context.Context, instance *opent.Instance) (string, string, string, error) {
	cidstr, err := actions.GetClusterIDStr(instance)
	if err != nil {
		return "", "", "", err
	}

	cid, err := strconv.ParseUint(cidstr, 10, 64)
	if err != nil {
		return "", "", "", err
	}

	cluster, err := p.comps.CoreSvc.Mgmt.GetCluster(ctx, cid)
	if err != nil {
		return "", "", "", err
	}
	ngCluster := cluster.GetNextGenCluster()

	vpcPeeringID, _ := instance.GetParam(opent.ParamVPCPeeringID)
	if len(vpcPeeringID) == 0 {
		return "", "", "", fmt.Errorf("vpc_peering_id is required")
	}

	return cidstr, ngCluster.GetDataplaneId(), vpcPeeringID, nil
}
