package utils_gorm

import (
	"ai_scheduler/internal/config"
	"database/sql"
	"fmt"
	"time"

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

func DBConn(c config.DB) (*gorm.DB, func()) {
	mysqlConn, err := sql.Open(c.Driver, c.Source)
	gormDB, err := gorm.Open(
		mysql.New(mysql.Config{Conn: mysqlConn}),
	)

	gormDB.Logger = NewCustomLogger(gormDB)
	if err != nil {
		panic("failed to connect database")
	}
	sqlDB, err := gormDB.DB()

	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(int(c.MaxIdle))

	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(int(c.MaxLifetime))

	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(time.Hour)

	return gormDB, func() {
		if mysqlConn != nil {
			fmt.Println("关闭 physicalGoodsDB")
			if err := mysqlConn.Close(); err != nil {
				fmt.Println("关闭 physicalGoodsDB 失败：", err)
			}
		}
	}
}
