//
// db.go
// Copyright (C) 2024 veypi <i@veypi.com>
// 2025-03-04 16:08:06
// Distributed under terms of the MIT license.
//

package cfg

import (
	"github.com/glebarez/sqlite"
	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var db *gorm.DB

func DB() *gorm.DB {
	if db == nil {
		var err error
		var conn gorm.Dialector
		switch Config.DB {
		case "mysql":
			conn = mysql.Open(Config.DSN)
		case "postgres":
			conn = postgres.Open(Config.DSN)
		default:
			conn = sqlite.Open(Config.DSN)
		}
		db, err = gorm.Open(conn,
			&gorm.Config{
				Logger: logger.Default.LogMode(logger.Silent),
			})
		if err != nil {
			panic(err)
		}
	}
	return db
}
