package data

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"voucher/internal/conf"
)

type GormDb struct {
	Client *gorm.DB
}

func NewGormDb(c *conf.Bootstrap) *GormDb {
	return &GormDb{
		Client: db(c.Data.Db),
	}
}

func db(data *conf.Data_Database) *gorm.DB {

	gormDB, err := gorm.Open(
		mysql.Open(data.Source),
		&gorm.Config{
			Logger:                 logger.Default.LogMode(logger.Info),
			SkipDefaultTransaction: true,
		},
	)

	if err != nil {
		panic("failed to connect database " + err.Error())
	}

	sqlDB, err := gormDB.DB()
	if err != nil {
		panic("failed to gormDB " + err.Error())
	}

	sqlDB.SetMaxIdleConns(50)
	sqlDB.SetMaxOpenConns(200)

	return gormDB
}
