<?php
/**
 * Test router for PHP's built-in server.
 *
 * Only the Supabase data helpers are replaced (with a local Postgres). The real
 * includes/auth.php runs untouched — it verifies tokens over HTTP against a
 * local GoTrue stub — so the auth path under test is the production one.
 */
putenv('SUPABASE_URL=http://127.0.0.1:8789');
putenv('SUPABASE_ANON_KEY=test-anon');
putenv('SUPABASE_SERVICE_KEY=test-service');
putenv('CRON_SECRET=testsecret');
putenv('TOURNAMENT_NO_SHOW_SECONDS=2');
// The self-healing ticks are throttled to once every 15s in production.
// Disable the throttle here so the suite is deterministic rather than
// dependent on sleeping past an interval.
putenv('TOURNAMENT_TICK_SECONDS=0');

require_once __DIR__ . '/pgshim.php';

$__pg = new PgShim();
function supabase(?string $token = null): SupabaseClient { global $__pg; return $__pg; }
function supabaseService(): SupabaseClient { global $__pg; return $__pg; }
function supabaseRpc(string $fn, array $params = []): ?array {
    file_put_contents(__DIR__ . '/rpc.log', json_encode([$fn, $params]) . "\n", FILE_APPEND);
    if ($fn === 'can_player_queue') return ['allowed' => true];
    if ($fn === 'merge_game_state') {
        // Mirror the real function: shallow-merge the patch into game_state.
        global $__pg;
        $rows = $__pg->get($params['p_table'], ['id' => 'eq.' . $params['p_match_id'], 'select' => 'game_state', 'limit' => 1]);
        $gs = (is_array($rows) && !empty($rows) && is_array($rows[0]['game_state'] ?? null)) ? $rows[0]['game_state'] : [];
        foreach (($params['p_patch'] ?? []) as $k => $v) {
            if ($v === null) unset($gs[$k]); else $gs[$k] = $v;
        }
        $__pg->update($params['p_table'], ['game_state' => $gs], ['id' => 'eq.' . $params['p_match_id']]);
        return ['ok' => true];
    }
    return [];
}

$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$file = dirname(__DIR__) . $path;
if (!is_file($file)) { http_response_code(404); header('Content-Type: application/json'); echo json_encode(['error' => 'no route: ' . $path]); exit; }
require $file;
