package commands

import (
	"fmt"

	"github.com/muyue/muyue/internal/config"
	"github.com/spf13/cobra"
)

var configCmd = &cobra.Command{
	Use:   "config",
	Short: "Show/print config",
}

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

func runConfigGet(cmd *cobra.Command, args []string) error {
	cfg, err := config.Load()
	if err != nil {
		return err
	}
	key := args[0]
	fmt.Fprintf(cmd.OutOrStdout(), "%v\n", getConfigValue(cfg, key))
	return nil
}

func getConfigValue(cfg *config.MuyueConfig, key string) interface{} {
	switch key {
	case "version":
		return cfg.Version
	case "profile.name":
		return cfg.Profile.Name
	case "profile.email":
		return cfg.Profile.Email
	default:
		return nil
	}
}

func runConfigSet(cmd *cobra.Command, args []string) error {
	cfg, err := config.Load()
	if err != nil {
		return err
	}
	key, value := args[0], args[1]
	setConfigValue(cfg, key, value)
	return config.Save(cfg)
}

func setConfigValue(cfg *config.MuyueConfig, key, value string) {
	switch key {
	case "profile.name":
		cfg.Profile.Name = value
	case "profile.email":
		cfg.Profile.Email = value
	}
}