package cmd

import (
	"fmt"
	"os"

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

var initCmd = &cobra.Command{
	Use:   "init",
	Short: "Initialize CLI configuration and authenticate",
	Long: `Initialize the CLI with your Investibook API host and an API key.

Generate an API key in the Investibook web UI:
  Settings (⚙) → API Keys → Create key`,
	Run: func(cmd *cobra.Command, args []string) {
		apiURL, _ := cmd.Flags().GetString("api-host")
		apiKey, _ := cmd.Flags().GetString("api-key")
		profileName, _ := cmd.Flags().GetString("profile")

		if apiURL == "" || apiKey == "" {
			fmt.Fprintln(os.Stderr, "Both --api-host and --api-key are required")
			os.Exit(1)
		}

		client := api.New(apiURL, "")
		res, err := client.LoginWithAPIKey(apiKey)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Login failed: %v\n", err)
			os.Exit(1)
		}

		cfg, _ := config.Load()
		if cfg == nil {
			cfg = &config.Config{}
		}

		cfg.UpsertProfile(profileName, config.Profile{
			API:    apiURL,
			Token:  res.Token,
			APIKey: apiKey,
			Email:  res.Email,
		})
		cfg.SetActiveProfile(profileName)

		if err := config.Save(cfg); err != nil {
			fmt.Fprintf(os.Stderr, "Failed to save config: %v\n", err)
			os.Exit(1)
		}

		fmt.Printf("Authenticated as %s (profile: %s)\n", res.Email, profileName)
		fmt.Printf("  Config saved to %s\n", config.Path())
	},
}

func init() {
	initCmd.Flags().String("api-host", "https://investibook.tidbcloud.com", "Investibook API base URL")
	initCmd.Flags().String("api-key", "", "API key generated in the Investibook Settings → API Keys page")
	initCmd.Flags().String("profile", "default", "Profile name (e.g., dev, prod)")
	rootCmd.AddCommand(initCmd)
}
