package app

import (
	"errors"
	"os"
	"os/exec"

	"coopcloud.tech/abra/cli/internal"
	appPkg "coopcloud.tech/abra/pkg/app"
	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/log"
	"github.com/AlecAivazis/survey/v2"
	"github.com/urfave/cli"
)

var appConfigCommand = cli.Command{
	Name:      "config",
	Aliases:   []string{"cfg"},
	Usage:     "Edit app config",
	ArgsUsage: "<domain>",
	Flags: []cli.Flag{
		internal.DebugFlag,
	},
	Before:       internal.SubCommandBefore,
	BashComplete: autocomplete.AppNameComplete,
	Action: func(c *cli.Context) error {
		appName := c.Args().First()

		if appName == "" {
			internal.ShowSubcommandHelpAndError(c, errors.New("no app provided"))
		}

		files, err := appPkg.LoadAppFiles("")
		if err != nil {
			log.Fatal(err)
		}

		appFile, exists := files[appName]
		if !exists {
			log.Fatalf("cannot find app with name %s", appName)
		}

		ed, ok := os.LookupEnv("EDITOR")
		if !ok {
			edPrompt := &survey.Select{
				Message: "which editor do you wish to use?",
				Options: []string{"vi", "vim", "nvim", "nano", "pico", "emacs"},
			}
			if err := survey.AskOne(edPrompt, &ed); err != nil {
				log.Fatal(err)
			}
		}

		cmd := exec.Command(ed, appFile.Path)
		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		if err := cmd.Run(); err != nil {
			log.Fatal(err)
		}

		return nil
	},
}
