package cmd

import (
	"fmt"
	"log"
	"slices"

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

var sourceListCmd = &cobra.Command{
	Use:     "list",
	Aliases: []string{"ls"},
	Short:   "List sources",
	Long: `Print the list of sources.
`,
	Run: func(cmd *cobra.Command, args []string) {
		sourceList()
	},
}

var sourceListShowActions bool

func init() {
	sourceCmd.AddCommand(sourceListCmd)

	sourceListCmd.Flags().BoolVarP(&sourceListShowActions, "actions", "a", false, "Include source actions")
}

func sourceList() {
	db := openAndMigrateDb()

	names, err := core.GetSources(db)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	slices.Sort(names)

	if sourceListShowActions {
		sourceActions := make(map[string][]string)
		for _, name := range names {
			actions, err := core.GetActionsForSource(db, name)
			if err != nil {
				log.Fatalf("error: could not get actions for source %s: %v", name, err)
			}
			slices.SortFunc(actions, actionSort)
			sourceActions[name] = actions
		}
		for _, name := range names {
			fmt.Printf("%s %v\n", name, sourceActions[name])
		}
	} else {
		for _, name := range names {
			fmt.Println(name)
		}
	}
}