package initialize

import (
	"fmt"

	"kra/internal/conf"

	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
)

// GormSqlite 初始化SQLite数据库
func GormSqlite(s *conf.Sqlite) (*gorm.DB, error) {
	if s == nil || s.DbName == "" {
		return nil, fmt.Errorf("sqlite config is empty")
	}
	return initSqliteDatabase(s)
}

// GormSqliteByConfig 通过传入配置初始化SQLite数据库
func GormSqliteByConfig(s *conf.Sqlite) (*gorm.DB, error) {
	return initSqliteDatabase(s)
}

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

	dsn := SqliteDsn(s)
	gormConfig := GormConfig(s.Prefix, s.Singular, s.LogMode)

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

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

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

	return db, nil
}

// SqliteDsn 生成SQLite DSN
func SqliteDsn(s *conf.Sqlite) string {
	if s.Path != "" {
		return fmt.Sprintf("%s/%s", s.Path, s.DbName)
	}
	return s.DbName
}
