<?php
  header('Access-Control-Allow-Origin:*', false);
  header('Content-Type: application/json');
/*
 * Database connection configuration
 *
 * All API scripts include this file to obtain the shared $con handle.
 * Connection lifecycle is managed by DatabaseManager (singleton per PHP worker).
 *
 * Production recommendation:
 *   DB_USE_PGBOUNCER = true  → point PHP at PgBouncer (port 6432)
 *   DB_USE_PERSISTENT = false → let PgBouncer pool backend connections
 */

// ── PostgreSQL server (direct connection) ─────────────────────────────────────
define('DB_USER', "user=postgres");
define('DB_PASSWORD', "password=postgres");
define('DB_DATABASE', "dbname=mch_prod");
define('DB_SERVER', "host=172.16.1.222");
define('DB_PORT', "port=5432");

// ── Connection pooling / performance tuning ───────────────────────────────────
// Set DB_USE_PGBOUNCER=true in production and run PHP against PgBouncer (see POSTGRES_OPTIMIZATION.md)
define('DB_USE_PGBOUNCER', false);
define('DB_PGBOUNCER_HOST', '127.0.0.1');
define('DB_PGBOUNCER_PORT', 6432);

// PHP persistent connections — use only WITHOUT PgBouncer (not recommended at 180+ concurrency)
define('DB_USE_PERSISTENT', false);

// Retry failed connections (transient network / "too many connections")
define('DB_MAX_RETRIES', 3);
define('DB_CONNECT_TIMEOUT', 5);

// Log queries slower than this threshold (milliseconds)
define('DB_SLOW_QUERY_MS', 500);

// Set true only for debugging — logs every query duration
define('DB_LOG_ALL_QUERIES', false);

require_once __DIR__ . '/DatabaseManager.php';
require_once __DIR__ . '/db_helpers.php';

// Backward-compatible global used by all existing API scripts.
// Endpoints that use PDO-only bulk sync can define MCH_DB_SKIP_PG_CONNECT before including this file.
$con = null;
if (!defined('MCH_DB_SKIP_PG_CONNECT') || !MCH_DB_SKIP_PG_CONNECT) {
    try {
        $con = DatabaseManager::getInstance()->getConnection();
    } catch (RuntimeException $e) {
        die(json_encode(array(
            'success' => 0,
            'message' => 'Database connection failed',
            'error' => $e->getMessage(),
        )));
    }
}
