<?php

declare(strict_types=1);

final class HyroDatabase
{
    private static ?PDO $connection = null;

    public static function connection(): PDO
    {
        if (self::$connection instanceof PDO) {
            return self::$connection;
        }

        $configFile =
            HYRO_BASE_PATH . '/config/database.php';

        if (!is_file($configFile)) {
            throw new RuntimeException(
                'Database configuration file not found.'
            );
        }

        $config = require $configFile;

        $host = (string) ($config['host'] ?? '');
        $port = (int) ($config['port'] ?? 3306);
        $database =
            (string) ($config['database'] ?? '');
        $username =
            (string) ($config['username'] ?? '');
        $password =
            (string) ($config['password'] ?? '');
        $charset =
            (string) ($config['charset'] ?? 'utf8mb4');

        if (
            $host === '' ||
            $database === '' ||
            $username === ''
        ) {
            throw new RuntimeException(
                'Database configuration is incomplete.'
            );
        }

        $dsn = sprintf(
            'mysql:host=%s;port=%d;dbname=%s;charset=%s',
            $host,
            $port,
            $database,
            $charset
        );

        self::$connection = new PDO(
            $dsn,
            $username,
            $password,
            [
                PDO::ATTR_ERRMODE =>
                    PDO::ERRMODE_EXCEPTION,

                PDO::ATTR_DEFAULT_FETCH_MODE =>
                    PDO::FETCH_ASSOC,

                PDO::ATTR_EMULATE_PREPARES =>
                    false,
            ]
        );

        return self::$connection;
    }
}
