package database

import (
	"log"
	"log/slog"
	"os"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// Open 初始化 GORM 数据库连接并自动同步所有表结构。
func Open(dsn string) (*gorm.DB, error) {
	gormLogger := logger.New(
		log.New(os.Stdout, "", log.LstdFlags|log.Lmicroseconds),
		logger.Config{
			SlowThreshold:             500 * time.Millisecond,
			LogLevel:                    logger.Warn,
			IgnoreRecordNotFoundError:   true,
			Colorful:                    false,
		},
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: gormLogger,
	})
	if err != nil {
		return nil, err
	}

	sqlDB, err := db.DB()
	if err != nil {
		return nil, err
	}
	sqlDB.SetMaxIdleConns(5)
	sqlDB.SetMaxOpenConns(20)
	sqlDB.SetConnMaxLifetime(time.Hour)

	if err := autoMigrate(db); err != nil {
		return nil, err
	}
	slog.Info("db", "event", "ready", "migrate", "ok")
	return db, nil
}

func autoMigrate(db *gorm.DB) error {
	return db.AutoMigrate(
		&ProductRow{},
		&ProductCodeRow{},
		&OrderRow{},
		&SiteSettingRow{},
		&WishlistRow{},
		&ChatMessageRow{},
	)
}
