package server

import (
	"os"
	"path/filepath"

	"coopcloud.tech/abra/cli/internal"
	"coopcloud.tech/abra/pkg/client"
	"coopcloud.tech/abra/pkg/config"
	"github.com/sirupsen/logrus"
	"github.com/urfave/cli/v2"
)

var rmServer bool
var rmServerFlag = &cli.BoolFlag{
	Name:        "server",
	Aliases:     []string{"s"},
	Value:       false,
	Usage:       "Remove the actual server also",
	Destination: &rmServer,
}

func rmHetznerCloudVPS(c *cli.Context) error {
	logrus.Warn("NOT IMPLEMENTED - COMING SOON")
	return nil
}

var serverRemoveCommand = &cli.Command{
	Name:    "remove",
	Aliases: []string{"rm"},
	Usage:   "Remove a managed server",
	Description: `
This command removes a server from being managed by Abra.

Depending on whether you used a 3rd party provider to create this server ("abra
server new"), you can also destroy the virtual server as well. Pass
"--server/-s" to tell Abra to try to delete this VPS.

Otherwise, 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{
		rmServerFlag,
		internal.DNSProviderFlag,
	},
	Action: func(c *cli.Context) error {
		domainName, err := internal.ValidateDomain(c)
		if err != nil {
			logrus.Fatal(err)
		}

		if rmServer {
			if err := internal.EnsureServerProvider(); err != nil {
				logrus.Fatal(err)
			}

			switch internal.ServerProvider {
			case "capsul":
				logrus.Warn("capsul provider does not support automatic removal yet, sorry!")
			case "hetzner-cloud":
				if err := rmHetznerCloudVPS(c); err != nil {
					logrus.Fatal(err)
				}
			}

		}

		if err := client.DeleteContext(domainName); err != nil {
			logrus.Fatal(err)
		}

		if err := os.RemoveAll(filepath.Join(config.ABRA_SERVER_FOLDER, domainName)); err != nil {
			logrus.Fatal(err)
		}

		logrus.Infof("server at '%s' has been lost in time, like tears in rain", domainName)

		return nil
	},
}