package app

import (
	"fmt"

	"coopcloud.tech/abra/cli/internal"
	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/client"
	"coopcloud.tech/abra/pkg/log"
	"github.com/urfave/cli"
)

var targetPath string
var targetPathFlag = &cli.StringFlag{
	Name:        "target, t",
	Usage:       "Target path",
	Destination: &targetPath,
}

var appRestoreCommand = cli.Command{
	Name:      "restore",
	Aliases:   []string{"rs"},
	Usage:     "Restore an app backup",
	ArgsUsage: "<domain> <service>",
	Flags: []cli.Flag{
		internal.DebugFlag,
		internal.OfflineFlag,
		targetPathFlag,
	},
	Before:       internal.SubCommandBefore,
	BashComplete: autocomplete.AppNameComplete,
	Action: func(c *cli.Context) error {
		app := internal.ValidateApp(c)
		if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil {
			log.Fatal(err)
		}

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

		targetContainer, err := internal.RetrieveBackupBotContainer(cl)
		if err != nil {
			log.Fatal(err)
		}

		execEnv := []string{fmt.Sprintf("SERVICE=%s", app.Domain)}
		if snapshot != "" {
			log.Debugf("including SNAPSHOT=%s in backupbot exec invocation", snapshot)
			execEnv = append(execEnv, fmt.Sprintf("SNAPSHOT=%s", snapshot))
		}
		if targetPath != "" {
			log.Debugf("including TARGET=%s in backupbot exec invocation", targetPath)
			execEnv = append(execEnv, fmt.Sprintf("TARGET=%s", targetPath))
		}

		if err := internal.RunBackupCmdRemote(cl, "restore", targetContainer.ID, execEnv); err != nil {
			log.Fatal(err)
		}

		return nil
	},
}
