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

import (
	"encoding/json"
	"fmt"
	"os"

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

type versionResponse struct {
	Version                string `json:"version"`
	CavctlSupportedVersion string `json:"cavctl_supported_version"`
}

// versionCmd represents the version command
var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "displays remote cavaliba version",
	Long:  `Call cavaliba and displays instance version`,
	Run: func(cmd *cobra.Command, args []string) {

		target := APITarget{
			url:            viper.GetString("url") + "version/",
			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)

		var vr versionResponse
		if err := json.Unmarshal([]byte(result.body), &vr); err == nil {
			if vr.CavctlSupportedVersion != "" && vr.CavctlSupportedVersion != cavctl_version {
				fmt.Printf("NOTICE: server supports cavctl version %s, current version is %s\n",
					vr.CavctlSupportedVersion, cavctl_version)
			}
		}
	},
}

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