<?php
declare(strict_types=1);

class AddressesDatabase {
    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,
                ];

                self::$instance = new PDO(
                    $dsn,
                    self::$config['username'],
                    self::$config['password'],
                    $options
                );
            } catch (PDOException $e) {
                throw new RuntimeException("Addresses database connection failed: " . $e->getMessage());
            }
        }

        return self::$instance;
    }

    /**
     * Ferme la connexion à la base de données des adresses
     */
    public static function close(): void {
        self::$instance = null;
    }
}