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/v3"
)

var appRestartCommand = cli.Command{
	Name:      "restart",
	Aliases:   []string{"re"},
	Usage:     "Restart an app",
	UsageText: "abra app restart <domain> [<service>] [options]",
	Flags: []cli.Flag{
		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.`,
	ShellComplete: autocomplete.AppNameComplete,
	HideHelp:      true,
	Action: func(ctx context.Context, cmd *cli.Command) error {
		app := internal.ValidateApp(cmd)
		if err := app.Recipe.Ensure(false, false); err != nil {
			log.Fatal(err)
		}

		serviceName := cmd.Args().Get(1)
		if serviceName == "" && !internal.AllServices {
			err := errors.New("missing <service>")
			internal.ShowSubcommandHelpAndError(cmd, 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
	},
}
