package server

import (
	"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"
)

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

Abra will remove the internal bookkeeping (~/.abra/servers/...) and underlying
client connection context. This server will then be lost in time, like tears in
rain.`,
	Flags: []cli.Flag{
		internal.DebugFlag,
		internal.NoInputFlag,
		internal.OfflineFlag,
	},
	Before:       internal.SubCommandBefore,
	BashComplete: autocomplete.ServerNameComplete,
	Action: func(c *cli.Context) error {
		serverName := internal.ValidateServer(c)

		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
	},
}
