<?php
declare(strict_types=1);

require_once __DIR__ . '/MonitoredDatabase.php';
require_once __DIR__ . '/../Services/Security/AlertService.php';

use App\Services\Security\AlertService;

class Database {
    private static ?PDO $instance = null;
    private static array $config;

    public static function init(array $config): void {
        self::$config = $config;
    }

    public static function getInstance(): PDO {
        if (self::$instance === null) {
            try {
                $dsn = sprintf("mysql:host=%s;dbname=%s;charset=utf8mb4",
                    self::$config['host'],
                    self::$config['name']
                );
                
                $options = [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false,
                ];

                // Utiliser MonitoredDatabase pour le monitoring
                self::$instance = new MonitoredDatabase(
                    $dsn,
                    self::$config['username'],
                    self::$config['password'],
                    $options
                );
            } catch (PDOException $e) {
                // Ne PAS utiliser AlertService ici car il essaie d'utiliser la DB
                // Juste logger l'erreur directement
                error_log("Database connection failed: " . $e->getMessage() . 
                         " | Host: " . self::$config['host'] . 
                         " | Database: " . self::$config['name']);
                
                throw new RuntimeException("Database connection failed: " . $e->getMessage());
            }
        }

        return self::$instance;
    }
}