package cmd

import (
	"fmt"
	"log"
	"slices"

	"github.com/Jaculabilis/intake/core"
	"github.com/spf13/cobra"
)

var actionListCmd = &cobra.Command{
	Use:     "list",
	Aliases: []string{"ls"},
	Short:   "List actions on a source",
	Long: `List actions on a source.
`,
	Run: func(cmd *cobra.Command, args []string) {
		actionList()
	},
}

var actionListSource string
var actionListArgv bool

func init() {
	actionCmd.AddCommand(actionListCmd)

	actionListCmd.Flags().StringVarP(&actionListSource, "source", "s", "", "Source to list actions")
	actionListCmd.MarkFlagRequired("source")

	actionListCmd.Flags().BoolVarP(&actionListArgv, "argv", "a", false, "Include action command")
}

func actionList() {
	if actionListSource == "" {
		log.Fatal("error: --source is empty")
	}

	db := openAndMigrateDb()

	actions, err := core.GetActionsForSource(db, actionListSource)
	if err != nil {
		log.Fatal(err)
	}
	slices.SortFunc(actions, actionSort)

	if actionListArgv {
		actionArgv := make(map[string][]string)
		for _, name := range actions {
			argv, err := core.GetArgvForAction(db, actionListSource, name)
			if err != nil {
				log.Fatalf("error: could not get argv for source %s action %s: %v", actionListSource, name, err)
			}
			actionArgv[name] = argv
		}
		for _, name := range actions {
			fmt.Printf("%s %v\n", name, actionArgv[name])
		}

	} else {
		for _, action := range actions {
			fmt.Println(action)
		}
	}
}