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

import (
	"fmt"
	"os"

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

// permissionCmd represents the permission command
var permissionCmd = &cobra.Command{
	Use:     "permission",
	Short:   "displays permission information",
	Long:    `Call cavaliba permissions/ API endpoint and displays permission information. Use --id flag to specify a permission ID or --key flag to specify a key.`,
	Aliases: []string{"permissions"},
	Run: func(cmd *cobra.Command, args []string) {

		endpoint := "permissions/"

		// Check if --id flag was provided (priority over --key)
		if cmd.Flags().Changed("id") {
			endpoint = fmt.Sprintf("permissions/%d/", id)
		} else if cmd.Flags().Changed("key") {
			endpoint = fmt.Sprintf("permissions/%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)
		}

		PrintVerboseTarget(target)

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

		PrintVerboseResult(result)
		PrintOutput(result.body)

	},
}

func init() {
	rootCmd.AddCommand(permissionCmd)
}
