package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"

	"git.wntrmute.dev/mc/mcp/internal/auth"
	"git.wntrmute.dev/mc/mcp/internal/config"
)

func loginCmd() *cobra.Command {
	return &cobra.Command{
		Use:   "login",
		Short: "Authenticate to MCIAS, store token",
		RunE: func(cmd *cobra.Command, args []string) error {
			cfg, err := config.LoadCLIConfig(cfgPath)
			if err != nil {
				return fmt.Errorf("load config: %w", err)
			}

			scanner := bufio.NewScanner(os.Stdin)

			fmt.Print("Username: ")
			if !scanner.Scan() {
				if err := scanner.Err(); err != nil {
					return fmt.Errorf("read username: %w", err)
				}
				return fmt.Errorf("read username: unexpected end of input")
			}
			username := strings.TrimSpace(scanner.Text())

			fmt.Print("Password: ")
			if !scanner.Scan() {
				if err := scanner.Err(); err != nil {
					return fmt.Errorf("read password: %w", err)
				}
				return fmt.Errorf("read password: unexpected end of input")
			}
			password := strings.TrimSpace(scanner.Text())

			token, err := auth.Login(cfg.MCIAS.ServerURL, cfg.MCIAS.CACert, username, password)
			if err != nil {
				return fmt.Errorf("login: %w", err)
			}

			if err := auth.SaveToken(cfg.Auth.TokenPath, token); err != nil {
				return fmt.Errorf("save token: %w", err)
			}

			fmt.Println("Login successful.")
			return nil
		},
	}
}
