/*
Copyright © 2025 cavaliba.com
*/
package cmd

import (
	"fmt"
	"net/http"
	"os"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var stopTask bool
var taskState string

var taskCmd = &cobra.Command{
	Use:     "task",
	Short:   "displays task information",
	Long:    `Call cavaliba tasks/ API endpoint. Use --key <uuid> to specify a task. Use --key <uuid> --stop to stop a task. Use --state <state> to filter by state (QUEUED, RUNNING, DONE, FAILED, ABORTED).`,
	Aliases: []string{"tasks"},
	Run: func(cmd *cobra.Command, args []string) {

		if cmd.Flags().Changed("stop") && !cmd.Flags().Changed("key") {
			fmt.Println("error: --stop requires --key <uuid>")
			os.Exit(1)
		}

		endpoint := "tasks/"

		if cmd.Flags().Changed("key") {
			if stopTask {
				endpoint = fmt.Sprintf("tasks/%s/stop/", key)
				target := APITarget{
					url:            viper.GetString("url") + endpoint,
					method:         http.MethodPost,
					ssl_skipverify: viper.GetBool("ssl_skipverify"),
				}
				PrintVerboseTarget(target)
				result, err := CallAPI(target)
				if err != nil {
					PrintError(result, err)
					os.Exit(0)
				}
				PrintVerboseResult(result)
				PrintOutput(result.body)
				return
			}
			endpoint = fmt.Sprintf("tasks/%s/", key)
		}

		target := APITarget{
			url:            viper.GetString("url") + endpoint,
			ssl_skipverify: viper.GetBool("ssl_skipverify"),
		}

		err := AppendGlobalOptions(&target)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		if taskState != "" {
			target.url = target.url + "&state=" + taskState
		}

		PrintVerboseTarget(target)

		result, err := CallAPI(target)
		if err != nil {
			PrintError(result, err)
			os.Exit(0)
		}

		PrintVerboseResult(result)
		fmt.Println(result.body)
	},
}

func init() {
	taskCmd.Flags().BoolVar(&stopTask, "stop", false, "Stop a task (requires --key <uuid>)")
	taskCmd.Flags().StringVar(&taskState, "state", "", "Filter by state: QUEUED, RUNNING, DONE, FAILED, ABORTED")
	rootCmd.AddCommand(taskCmd)
}
