package server

import (
	"context"
	"os"
	"path/filepath"

	"coopcloud.tech/abra/cli/internal"
	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/client"
	"coopcloud.tech/abra/pkg/config"
	"coopcloud.tech/abra/pkg/log"
	"github.com/urfave/cli/v3"
)

var serverRemoveCommand = cli.Command{
	Name:      "remove",
	Aliases:   []string{"rm"},
	UsageText: "abra server remove <domain> [options]",
	Usage:     "Remove a managed server",
	Description: `Remove a managed server.

Abra will remove the internal bookkeeping ($ABRA_DIR/servers/...) and
underlying client connection context. This server will then be lost in time,
like tears in rain.`,
	Before:        internal.SubCommandBefore,
	ShellComplete: autocomplete.ServerNameComplete,
	HideHelp:      true,
	Action: func(ctx context.Context, cmd *cli.Command) error {
		serverName := internal.ValidateServer(cmd)

		if err := client.DeleteContext(serverName); err != nil {
			log.Fatal(err)
		}

		if err := os.RemoveAll(filepath.Join(config.SERVERS_DIR, serverName)); err != nil {
			log.Fatal(err)
		}

		log.Infof("%s is now lost in time, like tears in rain", serverName)

		return nil
	},
}
