package initialize

import (
	"time"

	"kra/internal/conf"

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

// GormConfig 创建GORM配置
func GormConfig(prefix string, singular bool, logMode string) *gorm.Config {
	return &gorm.Config{
		Logger: logger.Default.LogMode(parseLogLevel(logMode)),
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   prefix,
			SingularTable: singular,
		},
		DisableForeignKeyConstraintWhenMigrating: true,
	}
}

// GormConfigWithSlowThreshold 创建带慢查询阈值的GORM配置
func GormConfigWithSlowThreshold(prefix string, singular bool, logMode string, slowThreshold time.Duration) *gorm.Config {
	return &gorm.Config{
		Logger: logger.Default.LogMode(parseLogLevel(logMode)),
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   prefix,
			SingularTable: singular,
		},
		DisableForeignKeyConstraintWhenMigrating: true,
	}
}

// parseLogLevel 解析日志级别
func parseLogLevel(level string) logger.LogLevel {
	switch level {
	case "silent":
		return logger.Silent
	case "error":
		return logger.Error
	case "warn":
		return logger.Warn
	case "info":
		return logger.Info
	default:
		return logger.Info
	}
}

// NewDBByType 根据数据库类型创建数据库连接
func NewDBByType(dbType string, bootstrap *conf.Bootstrap) (*gorm.DB, error) {
	switch dbType {
	case "mysql":
		return GormMysql(bootstrap.Mysql)
	case "pgsql":
		return GormPgsql(bootstrap.Pgsql)
	case "sqlite":
		return GormSqlite(bootstrap.Sqlite)
	case "mssql":
		return GormMssql(bootstrap.Mssql)
	case "oracle":
		return GormOracle(bootstrap.Oracle)
	default:
		return GormMysql(bootstrap.Mysql)
	}
}
