package cmd

import (
	"log"

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

var actionAddCmd = &cobra.Command{
	Use:   "add [flags] -- argv...",
	Short: "Add an action to a source",
	Long: `Add an action to a source.
`,
	Run: func(cmd *cobra.Command, args []string) {
		actionAdd(stringArg(cmd, "source"), stringArg(cmd, "action"), getArgv(cmd, args))
	},
}

func init() {
	actionCmd.AddCommand(actionAddCmd)

	actionAddCmd.Flags().StringP("source", "s", "", "Source to add action")
	actionAddCmd.MarkFlagRequired("source")

	actionAddCmd.Flags().StringP("action", "a", "", "Action name")
	actionAddCmd.MarkFlagRequired("action")
}

// TODO: This is a duplicate of `action edit`, the action CLI should be simplified

func actionAdd(source string, action string, argv []string) {
	if source == "" {
		log.Fatal("error: --source is empty")
	}
	if action == "" {
		log.Fatal("error: --action is empty")
	}
	if len(argv) == 0 {
		log.Fatal("error: no argv provided")
	}

	db := openAndMigrateDb()

	err := core.SetAction(db, source, action, argv)
	if err != nil {
		log.Fatalf("error: failed to add action: %v", err)
	}

	log.Printf("Added action %s to source %s", action, source)
}