package main

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

	"golang.org/x/term"
)

// RunAuth performs interactive login and returns the session token.
func RunAuth(api *APIClient) (string, error) {
	reader := bufio.NewReader(os.Stdin)

	fmt.Println(TitleStyle.Render("🗑  Dumpster Chat TUI"))
	fmt.Println(HelpStyle.Render("  Log in to continue\n"))

	fmt.Print("  Email: ")
	email, _ := reader.ReadString('\n')
	email = strings.TrimSpace(email)

	var password string

	fmt.Print("  Password: ")
	pwBytes, err := term.ReadPassword(int(syscall.Stdin))
	if err != nil {
		// Fallback to plain read
		var pwLine string
		fmt.Scanln(&pwLine)
		password = strings.TrimSpace(pwLine)
		fmt.Println()
		if password == "" {
			return "", fmt.Errorf("read password: %w", err)
		}
	} else {
		fmt.Println() // newline after password
		password = strings.TrimSpace(string(pwBytes))
	}

	if email == "" || password == "" {
		return "", fmt.Errorf("email and password are required")
	}

	lr, err := api.Login(email, password)
	if err != nil {
		return "", fmt.Errorf("login failed: %w", err)
	}

	_ = lr // user ID available if needed
	fmt.Println(SuccessStyle.Render("  ✓ Logged in successfully"))

	return api.SessionToken, nil
}
