package initialize

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
	"wails-app/internal/config"
	"wails-app/internal/global"
	"wails-app/internal/initialize/internal"
)

// GormSqlite 初始化Sqlite数据库
func GormSqlite() *gorm.DB {
	s := global.GVA_CONFIG.Sqlite
	if s.Dbname == "" {
		return nil
	}

	// Resolve path: empty = %APPDATA%/smart-parking/
	if s.Path == "" {
		if appData := os.Getenv("APPDATA"); appData != "" {
			s.Path = appData
		} else {
			// Fallback: exe directory
			if exePath, err := os.Executable(); err == nil {
				s.Path = filepath.Dir(exePath)
			}
		}
		s.Path = filepath.Join(s.Path, "smart-parking")
	}

	// Ensure directory exists
	if err := os.MkdirAll(s.Path, 0755); err != nil {
		panic(fmt.Errorf("failed to create SQLite db directory %s: %w", s.Path, err))
	}

	dsn := filepath.Join(s.Path, s.Dbname+".db")

	if db, err := gorm.Open(sqlite.Open(dsn), internal.Gorm.Config(s.Prefix, s.Singular)); err != nil {
		panic(err)
	} else {
		sqlDB, _ := db.DB()
		sqlDB.SetMaxIdleConns(s.MaxIdleConns)
		sqlDB.SetMaxOpenConns(s.MaxOpenConns)
		return db
	}
}

// GormSqliteByConfig 初始化Sqlite数据库用过传入配置
func GormSqliteByConfig(s config.Sqlite) *gorm.DB {
	if s.Dbname == "" {
		return nil
	}

	if db, err := gorm.Open(sqlite.Open(s.Dsn()), internal.Gorm.Config(s.Prefix, s.Singular)); err != nil {
		panic(err)
	} else {
		sqlDB, _ := db.DB()
		sqlDB.SetMaxIdleConns(s.MaxIdleConns)
		sqlDB.SetMaxOpenConns(s.MaxOpenConns)
		return db
	}
}
