<?php

declare(strict_types=1);

/**
 * Configuration de la base de données pour BAO
 * Charge les paramètres depuis le fichier .env
 */
class DatabaseConfig {
    private static ?self $instance = null;
    private array $config;

    private function __construct() {
        $this->loadEnv();
    }

    public static function getInstance(): self {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function loadEnv(): void {
        $envPath = __DIR__ . '/.env';

        if (!file_exists($envPath)) {
            throw new RuntimeException("Fichier .env introuvable. Copiez .env.example vers .env et configurez-le.");
        }

        $lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            // Ignorer les commentaires
            if (strpos(trim($line), '#') === 0) {
                continue;
            }

            // Parser les variables
            if (strpos($line, '=') !== false) {
                list($key, $value) = explode('=', $line, 2);
                $key = trim($key);
                $value = trim($value);
                $this->config[$key] = $value;
            }
        }
    }

    public function get(string $key, $default = null) {
        return $this->config[$key] ?? $default;
    }

    public function getEncryptionKey(): string {
        $key = $this->get('ENCRYPTION_KEY');
        if (empty($key)) {
            throw new RuntimeException("ENCRYPTION_KEY manquante dans .env");
        }
        return $key;
    }

    public function getEnvironmentConfig(string $env): array {
        $env = strtoupper($env);

        $enabled = $this->get("{$env}_ENABLED", 'false');
        if ($enabled !== 'true') {
            throw new RuntimeException("Environnement {$env} désactivé dans .env");
        }

        return [
            'use_vpn' => $this->get("{$env}_USE_VPN", 'false') === 'true',
            'ssh_host' => $this->get("{$env}_SSH_HOST"),
            'ssh_port_local' => (int)$this->get("{$env}_SSH_PORT_LOCAL"),
            'host' => $this->get("{$env}_DB_HOST"),
            'port' => (int)$this->get("{$env}_DB_PORT"),
            'name' => $this->get("{$env}_DB_NAME"),
            'user' => $this->get("{$env}_DB_USER"),
            'pass' => $this->get("{$env}_DB_PASS"),
        ];
    }

    public function getAvailableEnvironments(): array {
        $envs = [];
        foreach (['DVA', 'RCA', 'PRA'] as $env) {
            if ($this->get("{$env}_ENABLED") === 'true') {
                $envs[] = $env;
            }
        }
        return $envs;
    }
}
