package database

import (
	"fmt"
	"log"
	"strings"
	"xboard-go/internal/config"
	"xboard-go/internal/model"

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

var DB *gorm.DB

func InitDB() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.AppConfig.DBUser,
		config.AppConfig.DBPass,
		config.AppConfig.DBHost,
		config.AppConfig.DBPort,
		config.AppConfig.DBName,
	)

	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger:                                   logger.Default.LogMode(gormLogLevel(config.AppConfig.LogLevel)),
		DisableForeignKeyConstraintWhenMigrating: true,
	})

	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}

	if err := DB.AutoMigrate(
		&model.RealNameAuth{},
		&model.UserOnlineDevice{},
		&model.UserIPv6Subscription{},
	); err != nil {
		log.Fatalf("Failed to migrate database tables: %v", err)
	}

	if config.IsLogLevelEnabled(config.AppConfig.LogLevel, "info") {
		log.Println("Database connection established")
	}
}

func gormLogLevel(level string) logger.LogLevel {
	switch strings.ToLower(strings.TrimSpace(level)) {
	case "debug":
		return logger.Info
	case "info":
		return logger.Warn // Site request logs are handled by Gin, suppress GORM SQL logs in info
	case "warn":
		return logger.Warn
	case "error":
		return logger.Error
	case "silent":
		return logger.Silent
	default:
		return logger.Warn
	}
}
