package app

import (
	"fmt"

	"context"

	"coopcloud.tech/abra/pkg/config"

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

var appRollbackCommand = &cli.Command{
	Name:      "rollback",
	Usage:     "Roll an app back to a previous version",
	Aliases:   []string{"r"},
	ArgsUsage: "[<version>]",
	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)
		}
	},
	Action: func(c *cli.Context) error {
		app := internal.ValidateApp(c)

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

		recipeMeta, err := catalogue.GetRecipeMeta(app.Type)
		if err != nil {
			logrus.Fatal(err)
		}
		if len(recipeMeta.Versions) == 0 {
			logrus.Fatalf("no catalogue versions available for '%s'", app.Type)
		}

		deployedVersions, isDeployed, err := appPkg.DeployedVersions(ctx, cl, app)
		if err != nil {
			logrus.Fatal(err)
		}
		if !isDeployed {
			logrus.Fatalf("'%s' is not deployed?", app.Name)
		}
		if _, exists := deployedVersions["app"]; !exists {
			logrus.Fatalf("no versioned 'app' service for '%s', cannot determine version", app.Name)
		}

		version := c.Args().Get(1)
		if version == "" {
			// TODO:
			// using deployedVersions["app"], get index+1 version from catalogue
			// otherwise bail out saying there is nothing to rollback to
		} else {
			// TODO
			// ensure this version is listed in the catalogue
			// ensure this version is "older" (lower down in the list)
		}

		// TODO
		// display table of existing state and expected state and prompt
		// run the deployment with this target version!

		logrus.Fatal("command not implemented yet, coming soon TM")

		return nil
	},
}