<?php

declare(strict_types=1);

/**
 * 前台／後台共用的 fate PDO 取得（db.php 載入後寫入 $GLOBALS['pdo']）。
 */
function fate_bootstrap_pdo(?string &$connectError = null): ?PDO
{
    if (isset($GLOBALS['fate_app_pdo']) && $GLOBALS['fate_app_pdo'] instanceof PDO) {
        return $GLOBALS['fate_app_pdo'];
    }

    try {
        require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'pdo.php';
        if (isset($pdo) && $pdo instanceof PDO) {
            $GLOBALS['pdo'] = $pdo;
            $GLOBALS['fate_app_pdo'] = $pdo;

            return $pdo;
        }
        if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
            $GLOBALS['fate_app_pdo'] = $GLOBALS['pdo'];

            return $GLOBALS['pdo'];
        }
        $connectError = '未取得 PDO（請檢查 config/db.php 或 FATE_DB_* 環境變數）';
    } catch (Throwable $e) {
        $connectError = $e->getMessage();
    }

    return null;
}

/** @deprecated 請改用 fate_bootstrap_pdo() */
function fate_app_pdo(?string &$connectError = null): ?PDO
{
    return fate_bootstrap_pdo($connectError);
}
