package app

import (
	"context"
	"errors"
	"fmt"

	"coopcloud.tech/abra/cli/internal"
	appPkg "coopcloud.tech/abra/pkg/app"
	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/client"
	"coopcloud.tech/abra/pkg/log"
	upstream "coopcloud.tech/abra/pkg/upstream/service"
	stack "coopcloud.tech/abra/pkg/upstream/stack"
	"github.com/urfave/cli"
)

var appRestartCommand = cli.Command{
	Name:      "restart",
	Aliases:   []string{"re"},
	Usage:     "Restart an app",
	ArgsUsage: "<domain> [<service>]",
	Flags: []cli.Flag{
		internal.DebugFlag,
		internal.OfflineFlag,
		internal.AllServicesFlag,
	},
	Before: internal.SubCommandBefore,
	Description: `
This command restarts services within a deployed app.

Run "abra app ps <domain>" to see a list of service names.

Pass "--all-services/-a" to restart all services.

EXAMPLE:

    abra app restart example.com app`,
	BashComplete: autocomplete.AppNameComplete,
	Action: func(c *cli.Context) error {
		app := internal.ValidateApp(c)
		if err := app.Recipe.Ensure(false, false); err != nil {
			log.Fatal(err)
		}

		serviceName := c.Args().Get(1)
		if serviceName == "" && !internal.AllServices {
			err := errors.New("missing <service>")
			internal.ShowSubcommandHelpAndError(c, err)
		}

		if serviceName != "" && internal.AllServices {
			log.Fatal("cannot use <service> and --all-services together")
		}

		var serviceNames []string
		if internal.AllServices {
			var err error
			serviceNames, err = appPkg.GetAppServiceNames(app.Name)
			if err != nil {
				log.Fatal(err)
			}
		} else {
			serviceNames = append(serviceNames, serviceName)
		}

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

		deployMeta, err := stack.IsDeployed(context.Background(), cl, app.StackName())
		if err != nil {
			log.Fatal(err)
		}

		if !deployMeta.IsDeployed {
			log.Fatalf("%s is not deployed?", app.Name)
		}

		for _, serviceName := range serviceNames {
			stackServiceName := fmt.Sprintf("%s_%s", app.StackName(), serviceName)

			log.Debugf("attempting to scale %s to 0", stackServiceName)

			if err := upstream.RunServiceScale(context.Background(), cl, stackServiceName, 0); err != nil {
				log.Fatal(err)
			}

			if err := stack.WaitOnService(context.Background(), cl, stackServiceName, app.Name); err != nil {
				log.Fatal(err)
			}

			log.Debugf("%s has been scaled to 0", stackServiceName)
			log.Debugf("attempting to scale %s to 1", stackServiceName)

			if err := upstream.RunServiceScale(context.Background(), cl, stackServiceName, 1); err != nil {
				log.Fatal(err)
			}

			if err := stack.WaitOnService(context.Background(), cl, stackServiceName, app.Name); err != nil {
				log.Fatal(err)
			}

			log.Debugf("%s has been scaled to 1", stackServiceName)
			log.Infof("%s service successfully restarted", serviceName)
		}

		return nil
	},
}
