package common

import (
	"fmt"
	"log"
	"time"

	"github.com/gothinkster/golang-gin-realworld-example-app/config"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// InitMySQL initializes MySQL database connection
func InitMySQL() *gorm.DB {
	cfg := config.AppConfig
	if cfg == nil {
		log.Fatal("Config not loaded. Please call config.Load() first")
	}

	// Build DSN
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		cfg.DBUser,
		cfg.DBPassword,
		cfg.DBHost,
		cfg.DBPort,
		cfg.DBName,
	)

	// Open database connection
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		log.Fatal("Failed to connect to MySQL:", err)
	}

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

	// Set connection pool parameters
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Hour)

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

	log.Println("✓ MySQL connected successfully")
	DB = db
	return DB
}

// InitRedis initializes Redis client (you'll need to add redis package)
func InitRedis() {
	// TODO: Add Redis initialization
	// You'll need to add github.com/redis/go-redis/v9
	log.Println("✓ Redis initialization skipped (add go-redis package)")
}
