package db

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/joho/godotenv"
)

// DB is the global database connection pool
var DB *sql.DB

func InitDB() (*sql.DB, error) {
	// Load environment variables from .env file
	err := godotenv.Load()
	if err != nil {
		return nil, fmt.Errorf("error loading .env file: %v", err)
	}

	// Get connection details from environment variables
	connStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true",
		os.Getenv("DB_USER"),
		os.Getenv("DB_PASSWORD"),
		os.Getenv("DB_HOST"),
		os.Getenv("DB_PORT"),
		os.Getenv("DB_NAME"),
	)

	// Open the database connection
	DB, err = sql.Open("mysql", connStr)
	if err != nil {
		return nil, fmt.Errorf("error opening database: %v", err)
	}
	// Set connection pool parameters
	DB.SetMaxOpenConns(100)                // Maximum number of open connections to the database
	DB.SetMaxIdleConns(100)                // Maximum number of connections in the idle connection pool
	DB.SetConnMaxLifetime(5 * time.Minute) // Maximum amount of time a connection may be reused

	// Check if the database connection is working
	if err := DB.Ping(); err != nil {
		log.Printf("Database connection lost: %v. Reconnecting...", err)
		DB, err = InitDB()
		if err != nil {
			log.Printf("Failed to reconnect to database: %v", err)
		}
	}

	log.Print("Database connected successfully!")
	return DB, nil
}
