package storage

import (
	"fmt"
	"os"
	"path/filepath"
	"sync"
	"time"
	"u-desk/internal/common"
	"u-desk/internal/storage/models"

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

var globalDB *gorm.DB
var initOnce sync.Once

func Init() (*gorm.DB, error) {
	return InitFast()
}

func InitFast() (*gorm.DB, error) {
	if globalDB != nil {
		return globalDB, nil
	}
	var initErr error
	initOnce.Do(func() {
		dataDir := common.GetUserDataDir()
		if e := os.MkdirAll(dataDir, 0755); e != nil {
			initErr = e
			return
		}

		dbPath := filepath.Join(dataDir, "app.db")
		db, e := gorm.Open(sqlite.Open(dbPath+"?_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)&_pragma=cache_size(-64000)&_pragma=temp_store(MEMORY)&_pragma=mmap_size(30000000000)&_pragma=page_size(4096)&_pragma=foreign_keys(1)"), &gorm.Config{
			Logger:                 logger.Default.LogMode(logger.Silent),
			SkipDefaultTransaction: true,
			PrepareStmt:            true,
		})
		if e != nil {
			initErr = e
			return
		}

		sqlDB, e := db.DB()
		if e != nil {
			initErr = fmt.Errorf("获取底层SQL数据库失败: %v", e)
			return
		}
		sqlDB.SetMaxOpenConns(1)
		sqlDB.SetMaxIdleConns(1)
		sqlDB.SetConnMaxLifetime(time.Hour)

		if e := db.AutoMigrate(&models.AppConfig{}, &models.ConnectionProfile{}); e != nil {
			initErr = e
			return
		}
		globalDB = db
	})
	if initErr != nil {
		return nil, initErr
	}
	return globalDB, nil
}

func GetDB() *gorm.DB {
	return globalDB
}
