/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"encoding/json"

	log "github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"mortons.site/tps/internal/client"
	"mortons.site/tps/internal/properties"
)

// updateCmd represents the update command
var updateCmd = &cobra.Command{
	Use:    "update [name] [value]",
	Short:  "Update or Create a property",
	Long:   `Update or create new properties using the Tenant Properties Service`,
	PreRun: toggleDebug,
	Args:   cobra.ExactArgs(2),
	RunE: func(cmd *cobra.Command, args []string) error {
		p := []properties.PropertyUpdateOrCreate{{Type: "vcfg:PropertyUpdateOrCreate", Name: args[0], Value: args[1]}}
		pJSON, err := json.Marshal(p)
		if err != nil {
			return err
		}
		log.Debug(string(pJSON))

		hostname := viper.GetString("hostname")
		username := viper.GetString("username")
		password := viper.GetString("password")
		clientId := viper.GetString("clientId")

		err = client.UpdateProperty(&client.Config{Hostname: hostname, Username: username, Password: password, ClientID: clientId}, p)

		if err != nil {
			return err
		}
		return nil
	},
}

func init() {
	rootCmd.AddCommand(updateCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// updateCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// updateCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
