package app

import (
	"fmt"

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

var appUndeployCommand = &cli.Command{
	Name:    "undeploy",
	Aliases: []string{"u"},
	Usage:   "Undeploy an app",
	Description: `
This does not destroy any of the application data. However, you should remain
vigilant, as your swarm installation will consider any previously attached
volumes as eligiblef or pruning once undeployed.
`,
	Action: func(c *cli.Context) error {
		app := internal.ValidateApp(c)

		cl, err := client.New(app.Server)
		if err != nil {
			logrus.Fatal(err)
		}

		rmOpts := stack.Remove{Namespaces: []string{app.StackName()}}
		if err := stack.RunRemove(c.Context, cl, rmOpts); err != nil {
			logrus.Fatal(err)
		}

		return nil
	},
	BashComplete: func(c *cli.Context) {
		appNames, err := config.GetAppNames()
		if err != nil {
			logrus.Warn(err)
		}
		if c.NArg() > 0 {
			return
		}
		for _, a := range appNames {
			fmt.Println(a)
		}
	},
}