package app

import (
	"fmt"
	"sort"

	"coopcloud.tech/abra/cli/internal"
	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/formatter"
	"coopcloud.tech/abra/pkg/log"
	"github.com/spf13/cobra"
)

var AppEnvCommand = &cobra.Command{
	Use:     "env <app> [flags]",
	Aliases: []string{"e"},
	Short:   "Show app .env values",
	Example: "  abra app env 1312.net",
	Args:    cobra.ExactArgs(1),
	ValidArgsFunction: func(
		cmd *cobra.Command,
		args []string,
		toComplete string) ([]string, cobra.ShellCompDirective) {
		return autocomplete.AppNameComplete()
	},
	Run: func(cmd *cobra.Command, args []string) {
		app := internal.ValidateApp(args)

		if err := app.Recipe.Ensure(internal.GetEnsureContext()); err != nil {
			log.Fatal(err)
		}

		var envKeys []string
		for k := range app.Env {
			envKeys = append(envKeys, k)
		}

		sort.Strings(envKeys)

		var rows [][]string
		for _, k := range envKeys {
			rows = append(rows, []string{k, app.Env[k]})
		}

		overview := formatter.CreateOverview("ENV OVERVIEW", rows)
		fmt.Println(overview)
	},
}
