// Package main provides an example of authentication integration.
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/jfraeys/fetch_ml/internal/auth"
	"github.com/jfraeys/fetch_ml/internal/fileutil"
	"gopkg.in/yaml.v3"
)

// Example: How to integrate auth into TUI startup
func checkAuth(configFile string) error {
	// Load config
	data, err := fileutil.SecureFileRead(configFile)
	if err != nil {
		return fmt.Errorf("failed to read config: %w", err)
	}

	var cfg struct {
		Auth auth.Config `yaml:"auth"`
	}

	if err := yaml.Unmarshal(data, &cfg); err != nil {
		return fmt.Errorf("failed to parse config: %w", err)
	}

	// If auth disabled, proceed normally
	if !cfg.Auth.Enabled {
		fmt.Println("Authentication disabled - proceeding normally")
		return nil
	}

	// Check for API key
	apiKey := os.Getenv("FETCH_ML_API_KEY")
	if apiKey == "" {
		apiKey = getAPIKeyFromUser()
	}

	// Validate API key
	user, err := cfg.Auth.ValidateAPIKey(apiKey)
	if err != nil {
		return fmt.Errorf("authentication failed: %w", err)
	}

	fmt.Printf("Authenticated as: %s", user.Name)
	if user.Admin {
		fmt.Println(" (admin)")
	} else {
		fmt.Println()
	}

	return nil
}

func getAPIKeyFromUser() string {
	fmt.Print("Enter API key: ")
	var key string
	_, _ = fmt.Scanln(&key)
	return key
}

// Example usage in main()
func exampleMain() {
	configFile := "config_dev.yaml"

	// Check authentication first
	if err := checkAuth(configFile); err != nil {
		log.Fatalf("Authentication failed: %v", err)
	}

	// Proceed with normal TUI initialization
	fmt.Println("Starting TUI...")
}

func main() {
	exampleMain()
}
