<?php

class Database
{
    private static ?PDO $connection = null;

    public static function connection(): PDO
    {
        if (self::$connection === null) {
            $dsn = 'mysql:host=' . DB_HOST;

            if (defined('DB_PORT') && DB_PORT !== '') {
                $dsn .= ';port=' . DB_PORT;
            }

            $dsn .= ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET;

            try {
                self::$connection = new PDO($dsn, DB_USER, DB_PASS, [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false,
                ]);
            } catch (PDOException $exception) {
                if (defined('APP_DEBUG') && APP_DEBUG) {
                    throw $exception;
                }

                throw new RuntimeException('The service is temporarily unavailable. Please confirm the installation and database configuration.', 0, $exception);
            }
        }

        return self::$connection;
    }
}
