package database

import (
	"fmt"
	"jannex/admin-dashboard-backend/modules/config"
	"jannex/admin-dashboard-backend/modules/structs"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

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(&structs.User{})
	db.AutoMigrate(&structs.UserSession{})
	db.AutoMigrate(&structs.GroupTasks{})
	db.AutoMigrate(&structs.GroupTaskSteps{})
	db.AutoMigrate(&structs.Scanner{})
	db.AutoMigrate(&structs.Role{})
	db.AutoMigrate(&structs.RolePermission{})
	db.AutoMigrate(&structs.UserApiKey{})
	db.AutoMigrate(&structs.EquipmentDocumentation{})
}
