package main

import (
	"context"
	"fmt"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called when the app starts
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx
	if err := initDB(); err != nil {
		fmt.Printf("Database initialization failed: %v\n", err)
	}
}

// shutdown is called when the app is closing
func (a *App) shutdown(ctx context.Context) {}

// --- Game CRUD via SQLite ---

// GetAllGames returns all user-defined games
func (a *App) GetAllGames() []Game {
	return getAllGamesDB()
}

// GetActiveGameID returns the currently active game ID
func (a *App) GetActiveGameID() string {
	return getActiveGameID()
}

// SetActiveGame sets the active game and saves
func (a *App) SetActiveGame(gameID string) error {
	return setActiveGameID(gameID)
}

// AddGame creates a new game and saves
func (a *App) AddGame(game Game) (Game, error) {
	err := addGameDB(&game)
	return game, err
}

// UpdateGame updates an existing game's config
func (a *App) UpdateGame(game Game) error {
	return updateGameDB(&game)
}

// DeleteGame removes a game by ID
func (a *App) DeleteGame(gameID string) error {
	err := deleteGameDB(gameID)
	if err != nil {
		return err
	}

	if a.GetActiveGameID() == gameID {
		games := a.GetAllGames()
		if len(games) > 0 {
			a.SetActiveGame(games[0].ID)
		} else {
			a.SetActiveGame("")
		}
	}
	return nil
}

// --- Connection & API ---

// TestConnection tests connectivity for a game
func (a *App) TestConnection(game Game) ConnectionResult {
	return testHTTPConnection(game)
}

// XRayConnection performs a request and returns the full body
func (a *App) XRayConnection(game Game) XRayResult {
	return XRayConnection(game)
}
