package database

import (
	"fmt"

	"git.ex.umbach.dev/LMS/libcore/models"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"lms.de/backend/modules/config"
)

var DB *gorm.DB

func InitDatabase() {
	cfg := config.Cfg

	var logMode logger.LogLevel

	if cfg.Debug {
		logMode = logger.Error
	} else {
		logMode = logger.Silent
	}

	db, err := gorm.Open(mysql.Open(
		fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", cfg.MariaDB.Username, cfg.MariaDB.Password, cfg.MariaDB.Hostname, cfg.MariaDB.Port, cfg.MariaDB.DatabaseName)),
		&gorm.Config{
			Logger: logger.Default.LogMode(logMode),
		})

	if err != nil {
		panic(err)
	}

	DB = db

	db.AutoMigrate(&models.Organization{})
	db.AutoMigrate(&models.Role{})
	db.AutoMigrate(&models.RolePermission{})
	db.AutoMigrate(&models.User{})
	db.AutoMigrate(&models.UserSession{})
	db.AutoMigrate(&models.Lesson{})
	db.AutoMigrate(&models.LessonContent{})
	db.AutoMigrate(&models.Question{})
	db.AutoMigrate(&models.QuestionLike{})
	db.AutoMigrate(&models.QuestionReply{})
	db.AutoMigrate(&models.QuestionReplyLike{})
}
