package cmd

import (
	"fmt"
	"os"
	"sort"

	"github.com/spf13/cobra"
	"github.com/tidbcloud/investibook/cli/internal/config"
)

var profileCmd = &cobra.Command{
	Use:   "profile",
	Short: "Manage authentication profiles",
}

var profileListCmd = &cobra.Command{
	Use:     "list",
	Aliases: []string{"ls"},
	Short:   "List all configured profiles",
	Run: func(cmd *cobra.Command, args []string) {
		cfg := mustLoadConfig()
		if len(cfg.Profiles) == 0 {
			fmt.Println("No profiles configured. Run: investibook init --profile <name> --api-host <url> --api-key <key>")
			return
		}
		names := make([]string, 0, len(cfg.Profiles))
		for name := range cfg.Profiles {
			names = append(names, name)
		}
		sort.Strings(names)
		for _, name := range names {
			p := cfg.Profiles[name]
			active := "  "
			if name == cfg.ActiveProfile {
				active = "* "
			}
			fmt.Printf("%s%-12s  %s  (%s)\n", active, name, p.API, p.Email)
		}
	},
}

var profileUseCmd = &cobra.Command{
	Use:   "use <profile>",
	Short: "Switch the active profile",
	Args:  cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		name := args[0]
		cfg := mustLoadConfig()
		if _, ok := cfg.Profiles[name]; !ok {
			fmt.Fprintf(os.Stderr, "Profile %q not found. Run: investibook init --profile %s --api-host <url> --api-key <key>\n", name, name)
			os.Exit(1)
		}
		cfg.SetActiveProfile(name)
		if err := config.Save(cfg); err != nil {
			fmt.Fprintf(os.Stderr, "Failed to save config: %v\n", err)
			os.Exit(1)
		}
		p := cfg.Profiles[name]
		fmt.Printf("Switched to profile %q (%s)\n", name, p.API)
	},
}

func init() {
	profileCmd.AddCommand(profileListCmd)
	profileCmd.AddCommand(profileUseCmd)
	rootCmd.AddCommand(profileCmd)
}
