package models

import (
	"log"
	"strings"

	"git.apinb.com/bsm-sdk/core/database/sql"
	"git.apinb.com/bsm-sdk/core/types"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DBService *gorm.DB

var migrateTables = []any{
	&MarketAgency{},
	&MarketSupply{},
}

func New(driver string, dsn []string, options *types.SqlOptions) (err error) {
	driver = strings.ToLower(driver)

	switch driver {
	case "mysql":
		DBService, err = NewMysql(dsn, options)
	case "postgres":
		DBService, err = NewPostgres(dsn, options)
	default:
		log.Fatalln("Unsupported database driver:", driver)
		return
	}

	if err != nil {
		log.Fatalln(err)
		return err
	}

	// auto migrate table.
	err = DBService.AutoMigrate(migrateTables...)
	if err != nil {
		log.Fatalln(err)
		return err
	}

	return
}

func NewMysql(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err error) {
	//set connection default val.
	options = sql.SetOptions(options)

	gormDb, err = gorm.Open(mysql.Open(dsn[0]), &gorm.Config{
		SkipDefaultTransaction: true,
	})
	if err != nil {
		return nil, err
	}

	if options.Debug {
		gormDb = gormDb.Debug()
	}

	// 获取通用数据库对象 sql.DB ，然后使用其提供的功能
	sqlDB, _ := gormDb.DB()
	// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
	sqlDB.SetMaxIdleConns(options.MaxIdleConns)
	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(options.MaxOpenConns)
	// SetConnMaxLifetime 设置了连接可复用的最大时间。
	sqlDB.SetConnMaxLifetime(options.ConnMaxLifetime)

	return gormDb, nil
}

func NewPostgres(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err error) {
	//set connection default val.
	options = sql.SetOptions(options)

	db, err := sql.NewPostgreSql(dsn[0], options)
	if err != nil {
		return nil, err
	}
	db = db.Debug()

	return db, nil
}
