package dao

import (
	"fmt"
	"kv_api/config"
	dbModel "kv_api/model/db"
	"time"

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

type Dao struct {
	c  *config.Config
	db *gorm.DB
}

func New(_c *config.Config) (dao *Dao, err error) {
	dao = &Dao{
		c: _c,
	}
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True",
		_c.MySQL.User, _c.MySQL.Password, _c.MySQL.Host, _c.MySQL.Port, _c.MySQL.Database)
	dao.db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: logger.Default.LogMode(logger.Silent),
	})
	if err != nil {
		return
	}
	sqlDB, err := dao.db.DB()
	if err != nil {
		return
	}
	sqlDB.SetMaxOpenConns(_c.MySQL.MaxConn)
	sqlDB.SetMaxIdleConns(_c.MySQL.MaxIdleConn)
	sqlDB.SetConnMaxIdleTime(time.Hour)
	err = dao.db.AutoMigrate(&dbModel.KVStorage{})
	if err != nil {
		return
	}

	return dao, nil
}
