package initialize

import (
	"fmt"

	"kra/internal/conf"

	oracle "github.com/dzwvip/gorm-oracle"
	"gorm.io/gorm"
)

// GormOracle 初始化Oracle数据库
func GormOracle(o *conf.Oracle) (*gorm.DB, error) {
	if o == nil || o.DbName == "" {
		return nil, fmt.Errorf("oracle config is empty")
	}
	return initOracleDatabase(o)
}

// GormOracleByConfig 通过传入配置初始化Oracle数据库
func GormOracleByConfig(o *conf.Oracle) (*gorm.DB, error) {
	return initOracleDatabase(o)
}

// initOracleDatabase 初始化Oracle数据库的辅助函数
func initOracleDatabase(o *conf.Oracle) (*gorm.DB, error) {
	if o.DbName == "" {
		return nil, nil
	}

	dsn := OracleDsn(o)
	gormConfig := GormConfig(o.Prefix, o.Singular, o.LogMode)

	db, err := gorm.Open(oracle.Open(dsn), gormConfig)
	if err != nil {
		return nil, err
	}

	sqlDB, err := db.DB()
	if err != nil {
		return nil, err
	}

	sqlDB.SetMaxIdleConns(int(o.MaxIdleConns))
	sqlDB.SetMaxOpenConns(int(o.MaxOpenConns))

	return db, nil
}

// OracleDsn 生成Oracle DSN
func OracleDsn(o *conf.Oracle) string {
	return fmt.Sprintf("oracle://%s:%s@%s:%s/%s?%s",
		o.Username, o.Password, o.Path, o.Port, o.DbName, o.Config)
}
