package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"

	"git.rouggy.com/rouggy/RaceBot/internal/config"
	"git.rouggy.com/rouggy/RaceBot/internal/database"
	"git.rouggy.com/rouggy/RaceBot/models"
	"git.rouggy.com/rouggy/RaceBot/server"
	"github.com/jinzhu/gorm"
)

func main() {

	// Get app path
	pwd, err := os.Getwd()

	configPath := filepath.Join(pwd, "config")
	cfg := config.New(configPath)

	database.SQLiteDBConnect(cfg.Config)
	defer func(db *gorm.DB) {
		err := db.Close()
		if err != nil {
			fmt.Println("Could not close the database")
		}
	}(database.GetDB())

	SQLiteMigrate()

	server := server.NewServer(cfg.Config.Host + ":" + cfg.Config.Port)
	server.Start(cfg.Config)
	if err != nil {
		fmt.Println("Could not start server")
	}

}

func SQLiteMigrate() {
	db := database.GetDB()
	db.LogMode(false)
	if err := db.AutoMigrate(&models.Release{}, &models.Race{}).Error; err != nil {
		panic("[Database] Failed migrating database: ")
	}
	log.Println("[Database] Database successfully migrated")
}