<?php

/**
 * Database helper functions for MCH API.
 *
 * These wrappers keep existing endpoint code readable while routing
 * execution through DatabaseManager for logging and connection reuse.
 */

/**
 * Release the database connection at end of request.
 * Replaces direct pg_close() calls — safe with persistent connections and PgBouncer.
 *
 * @param \PgSql\Connection|null $conn Optional; kept for backward compatibility with mch_db_release($con)
 */
function mch_db_release($conn = null)
{
    DatabaseManager::getInstance()->releaseConnection($conn);
}

/**
 * Execute a prepared statement with centralized timing and error logging.
 *
 * @param \PgSql\Connection $con      Connection (from $con global)
 * @param string            $stmtName Prepared statement name
 * @param string            $sql      SQL query
 * @param array             $params   Bound parameters
 * @param bool              $prepare  Whether to call pg_prepare
 * @return \PgSql\Result|false
 */
function mch_pg_execute($con, $stmtName, $sql, array $params = array(), $prepare = true)
{
    return DatabaseManager::getInstance()->executePrepared($stmtName, $sql, $params, $prepare);
}

/**
 * Run a callback inside a single database transaction.
 *
 * @param \PgSql\Connection $con      Connection (passed to callback)
 * @param callable $callback Function receiving $con
 * @return mixed
 */
function mch_db_transaction($con, callable $callback)
{
    return DatabaseManager::getInstance()->transaction($callback);
}
