package database

import (
	"fmt"
	"log"
	"time"

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

	"infogenie-backend/config"
	"infogenie-backend/internal/model"
)

var DB *gorm.DB

func Init(cfg config.DBConfig) error {
	logLevel := logger.Warn
	if config.Cfg.Env == "development" {
		logLevel = logger.Info
	}

	db, err := gorm.Open(mysql.Open(cfg.DSN()), &gorm.Config{
		Logger: logger.Default.LogMode(logLevel),
	})
	if err != nil {
		return fmt.Errorf("连接MySQL失败: %w", err)
	}

	sqlDB, err := db.DB()
	if err != nil {
		return fmt.Errorf("获取底层DB连接失败: %w", err)
	}

	sqlDB.SetMaxOpenConns(25)
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetConnMaxLifetime(5 * time.Minute)

	if err := sqlDB.Ping(); err != nil {
		return fmt.Errorf("Ping数据库失败: %w", err)
	}

	DB = db
	log.Printf("MySQL连接成功 [env=%s]: %s:%s/%s", config.Cfg.Env, cfg.Host, cfg.Port, cfg.Name)
	return nil
}

func AutoMigrate() error {
	return DB.AutoMigrate(
		&model.AIConfig{},
		&model.Site60sDisabled{},
		&model.SiteAIRuntime{},
		&model.Site60sUpstream{},
		&model.SiteAIModelDisabled{},
	)
}
