package control

import (
	"encoding/hex"
	"errors"

	rawclient "git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/rpc/client"
	"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-cli/internal/key"
	commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
	ircontrol "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/services/control/ir"
	ircontrolsrv "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/services/control/ir/server"
	"github.com/spf13/cobra"
)

var removeNodeCmd = &cobra.Command{
	Use:   "remove-node",
	Short: "Forces a node removal from netmap",
	Long:  "Forces a node removal from netmap via a notary request. It should be executed on other IR nodes as well.",
	Run:   removeNode,
}

func initControlIRRemoveNodeCmd() {
	initControlFlags(removeNodeCmd)

	flags := removeNodeCmd.Flags()
	flags.String("node", "", "Node public key as a hex string")
	_ = removeNodeCmd.MarkFlagRequired("node")
}

func removeNode(cmd *cobra.Command, _ []string) {
	pk := key.Get(cmd)
	c := getClient(cmd, pk)

	nodeKeyStr, _ := cmd.Flags().GetString("node")
	if len(nodeKeyStr) == 0 {
		commonCmd.ExitOnErr(cmd, "parsing node public key: ", errors.New("key cannot be empty"))
	}
	nodeKey, err := hex.DecodeString(nodeKeyStr)
	commonCmd.ExitOnErr(cmd, "can't decode node public key: %w", err)

	req := new(ircontrol.RemoveNodeRequest)
	req.SetBody(&ircontrol.RemoveNodeRequest_Body{
		Key: nodeKey,
	})

	commonCmd.ExitOnErr(cmd, "could not sign request: %w", ircontrolsrv.SignMessage(pk, req))

	var resp *ircontrol.RemoveNodeResponse
	err = c.ExecRaw(func(client *rawclient.Client) error {
		resp, err = ircontrol.RemoveNode(client, req)
		return err
	})
	commonCmd.ExitOnErr(cmd, "rpc error: %w", err)

	verifyResponse(cmd, resp.GetSignature(), resp.GetBody())

	cmd.Println("Node removed")
}