<?php

declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';

/**
 * Gestion de la connexion à la base de données
 */
class DatabaseConnection {
    private ?PDO $pdo = null;
    private array $config;
    private string $environment;

    public function __construct(string $environment) {
        $this->environment = strtoupper($environment);
        $dbConfig = DatabaseConfig::getInstance();
        $this->config = $dbConfig->getEnvironmentConfig($this->environment);
    }

    /**
     * Établit la connexion PDO
     */
    public function connect(): PDO {
        if ($this->pdo !== null) {
            return $this->pdo;
        }

        try {
            $dsn = sprintf(
                'mysql:host=%s;port=%d;dbname=%s;charset=utf8mb4',
                $this->config['host'],
                $this->config['port'],
                $this->config['name']
            );

            $options = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
            ];

            $this->pdo = new PDO(
                $dsn,
                $this->config['user'],
                $this->config['pass'],
                $options
            );

            return $this->pdo;

        } catch (PDOException $e) {
            throw new RuntimeException(
                "Impossible de se connecter à la base {$this->environment}: " . $e->getMessage()
            );
        }
    }

    /**
     * Retourne la connexion PDO active
     */
    public function getPdo(): PDO {
        if ($this->pdo === null) {
            $this->connect();
        }
        return $this->pdo;
    }

    /**
     * Ferme la connexion
     */
    public function close(): void {
        $this->pdo = null;
    }

    /**
     * Retourne le nom de l'environnement
     */
    public function getEnvironment(): string {
        return $this->environment;
    }

    /**
     * Retourne la configuration SSH pour le tunnel
     */
    public function getSshConfig(): array {
        return [
            'host' => $this->config['ssh_host'],
            'port_local' => $this->config['ssh_port_local'],
            'port_remote' => 3306,
        ];
    }

    /**
     * Vérifie si l'environnement utilise le VPN (pas besoin de tunnel SSH)
     */
    public function usesVpn(): bool {
        return $this->config['use_vpn'] ?? false;
    }

    /**
     * Teste la connexion
     */
    public function testConnection(): bool {
        try {
            $pdo = $this->connect();
            $stmt = $pdo->query('SELECT 1');
            return $stmt !== false;
        } catch (Exception $e) {
            return false;
        }
    }
}
