package main

import (
	"os"
	"path/filepath"

	"github.com/glebarez/sqlite"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var db *gorm.DB

// Setting represents simple key-value store for app configs
type Setting struct {
	Key   string `gorm:"primaryKey"`
	Value string
}

func initDB() error {
	homeDir, err := os.UserHomeDir()
	if err != nil {
		return err
	}
	configDir := filepath.Join(homeDir, ".betting-assistant")
	if err := os.MkdirAll(configDir, 0755); err != nil {
		return err
	}
	dbPath := filepath.Join(configDir, "data.db")

	db, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Silent),
	})
	if err != nil {
		return err
	}

	// Auto Migration
	if err := db.AutoMigrate(&Game{}, &Setting{}); err != nil {
		return err
	}

	// Insert defaults if empty
	var count int64
	db.Model(&Game{}).Count(&count)
	if count == 0 {
		insertDefaults()
	}

	return nil
}

func insertDefaults() {
	games := []Game{
		{ID: uuid.New().String(), Name: "地鼠挖宝 (Moles)", Icon: "🐹", URL: "http://127.0.0.1:8080/api/v1/moles/start", Token: ""},
	}
	db.Create(&games)

	db.Save(&Setting{Key: "active_game_id", Value: games[0].ID})
}

// -- DB Operations wrapped for app logic --

func getAllGamesDB() []Game {
	var games []Game
	db.Find(&games)
	return games
}

func getActiveGameID() string {
	var s Setting
	db.First(&s, "key = ?", "active_game_id")
	return s.Value
}

func setActiveGameID(id string) error {
	return db.Save(&Setting{Key: "active_game_id", Value: id}).Error
}

func addGameDB(game *Game) error {
	if game.ID == "" {
		game.ID = uuid.New().String()
	}
	return db.Create(game).Error
}

func updateGameDB(game *Game) error {
	return db.Save(game).Error
}

func deleteGameDB(id string) error {
	return db.Delete(&Game{}, "id = ?", id).Error
}
