package config

import (
	"fmt"
	"log"
	"os"

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

var DB *gorm.DB

// JWTSecret is the secret key used for signing JWT tokens
var JWTSecret = "your-secret-key-change-this-in-production" // Default value

func InitDB() {
	var err error

	// Try to get DSN from environment variable, otherwise use default
	dsn := os.Getenv("DB_DSN")
	if dsn == "" {
		dsn = "root:root@tcp(127.0.0.1:3306)/nl_blog?charset=utf8mb4&parseTime=True&loc=Local"
	}

	// Try to get JWT secret from environment variable
	if secret := os.Getenv("JWT_SECRET"); secret != "" {
		JWTSecret = secret
	}

	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Silent), // 禁用 GORM 日志，使用自定义日志
		// 不使用 NowFunc，因为我们使用模型钩子手动处理 int64 时间戳
	})
	if err != nil {
		log.Fatal("Failed to connect to database:", err)
	}

	sqlDB, err := DB.DB()
	if err != nil {
		log.Fatal("Failed to get underlying sql.DB:", err)
	}

	if err = sqlDB.Ping(); err != nil {
		log.Fatal("Failed to ping database:", err)
	}

	fmt.Println("Database connected successfully")
}

func CloseDB() {
	if DB != nil {
		sqlDB, err := DB.DB()
		if err == nil {
			sqlDB.Close()
		}
	}
}
