<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

function app_db_pdo(): PDO
{
    static $pdo = null;

    if ($pdo instanceof PDO) {
        return $pdo;
    }

    $host = app_env('DB_HOST', '');
    $database = app_env('DB_NAME', '');
    $user = app_env('DB_USER', '');
    $password = app_env('DB_PASS', '');
    $port = app_env('DB_PORT', '3306');

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

    $dsn = sprintf('mysql:host=%s;port=%s;dbname=%s;charset=utf8mb4', $host, $port, $database);
    $pdo = new PDO($dsn, $user, $password ?? '', [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => true,
    ]);

    return $pdo;
}
