package app

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

var appConfigCommand = cli.Command{
	Name:          "config",
	Aliases:       []string{"cfg"},
	Usage:         "Edit app config",
	UsageText:     "abra app config <domain> [options]",
	Before:        internal.SubCommandBefore,
	ShellComplete: autocomplete.AppNameComplete,
	HideHelp:      true,
	Action: func(ctx context.Context, cmd *cli.Command) error {
		appName := cmd.Args().First()

		if appName == "" {
			internal.ShowSubcommandHelpAndError(cmd, 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)
			}
		}

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

		return nil
	},
}
