package cmd

import (
	"context"
	"fmt"

	"gogs.dmsc.dev/arp/arp_cli/config"

	"github.com/AlecAivazis/survey/v2"
	"github.com/urfave/cli/v3"
)

// ConfigCommand returns the config command
func ConfigCommand() *cli.Command {
	return &cli.Command{
		Name:  "config",
		Usage: "Manage CLI configuration",
		Description: `View and manage the arp_cli configuration.

The configuration is stored in ~/.arp_cli/config.json and contains:
- Server URL
- Authentication token
- Logged-in user email`,
		Commands: []*cli.Command{
			{
				Name:   "view",
				Usage:  "Show current configuration",
				Action: configView,
			},
			{
				Name:   "set-url",
				Usage:  "Set the server URL",
				Action: configSetURL,
				Flags: []cli.Flag{
					&cli.StringFlag{
						Name:     "url",
						Aliases:  []string{"u"},
						Usage:    "Server URL",
						Required: true,
					},
				},
			},
			{
				Name:    "logout",
				Usage:   "Clear stored authentication token",
				Aliases: []string{"clear"},
				Action:  configLogout,
			},
		},
		Action: configView,
	}
}

func configView(ctx context.Context, cmd *cli.Command) error {
	cfg, err := config.Load()
	if err != nil {
		return fmt.Errorf("failed to load config: %w", err)
	}

	fmt.Println("Current Configuration:")
	fmt.Printf("  Server URL: %s\n", cfg.ServerURL)
	if cfg.UserEmail != "" {
		fmt.Printf("  Logged in as: %s\n", cfg.UserEmail)
	} else {
		fmt.Println("  Logged in as: (not authenticated)")
	}

	if cfg.Token != "" {
		// Show first/last few characters of token
		if len(cfg.Token) > 20 {
			fmt.Printf("  Token: %s...%s\n", cfg.Token[:10], cfg.Token[len(cfg.Token)-6:])
		} else {
			fmt.Println("  Token: (set)")
		}
	} else {
		fmt.Println("  Token: (not set)")
	}

	return nil
}

func configSetURL(ctx context.Context, cmd *cli.Command) error {
	url := cmd.String("url")

	cfg, err := config.Load()
	if err != nil {
		return fmt.Errorf("failed to load config: %w", err)
	}

	// If user is logged in, warn them
	if cfg.Token != "" {
		confirm := false
		prompt := &survey.Confirm{
			Message: "Changing the server URL will clear your authentication token. Continue?",
			Default: false,
		}
		if err := survey.AskOne(prompt, &confirm); err != nil {
			return err
		}
		if !confirm {
			fmt.Println("Aborted.")
			return nil
		}
		cfg.Token = ""
		cfg.UserEmail = ""
	}

	cfg.ServerURL = url
	if err := config.Save(cfg); err != nil {
		return fmt.Errorf("failed to save config: %w", err)
	}

	fmt.Printf("Server URL set to: %s\n", url)
	if cfg.Token == "" {
		fmt.Println("Please run 'arp_cli login' to authenticate with the new server.")
	}

	return nil
}

func configLogout(ctx context.Context, cmd *cli.Command) error {
	cfg, err := config.Load()
	if err != nil {
		return fmt.Errorf("failed to load config: %w", err)
	}

	if cfg.Token == "" {
		fmt.Println("No authentication token stored.")
		return nil
	}

	confirm := false
	prompt := &survey.Confirm{
		Message: "Are you sure you want to logout?",
		Default: true,
	}
	if err := survey.AskOne(prompt, &confirm); err != nil {
		return err
	}

	if !confirm {
		fmt.Println("Aborted.")
		return nil
	}

	if err := config.Clear(); err != nil {
		return fmt.Errorf("failed to clear config: %w", err)
	}

	fmt.Println("Logged out successfully.")
	return nil
}
