package database

import (
	"database/sql"
	"fmt"

	"git.umbach.dev/app-idea/rest-api/modules/config"
	log "github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func getConnectionString() string {
	cfg := &config.Cfg.Database

	return fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", cfg.Username, cfg.Password, cfg.Host, cfg.Database)
}

func InitDatabase() {
	sqlDB, err := sql.Open("mysql", getConnectionString())

	if err != nil {
		log.Fatalln("Database connection failed:", err)
	}

	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)

	gormDB, err := gorm.Open(mysql.New(mysql.Config{
		Conn: sqlDB,
	}), &gorm.Config{})

	if err != nil {
		log.Fatalln("Failed to open gorm ", err)
	}

	DB = gormDB

	log.Debugln("Database connected")
}
