#!/usr/bin/env php
<?php
/**
 * Logic tests for pay queue + inbound attach (no live panel / DB required).
 */
if (php_sapi_name() !== 'cli') {
    fwrite(STDERR, "CLI only\n");
    exit(1);
}

$root = dirname(__DIR__);
require_once $root . '/services/XuiV3ApiClient.php';
require_once $root . '/services/XuiV3Service.php';

$passed = 0;
$failed = 0;

function assertTrue($label, $cond, $detail = '')
{
    global $passed, $failed;
    if ($cond) {
        echo "[PASS] $label\n";
        $passed++;
        return;
    }
    echo "[FAIL] $label" . ($detail ? " — $detail" : '') . "\n";
    $failed++;
}

$ref = new ReflectionClass(XuiV3Service::class);
$parse = $ref->getMethod('parseInboundIdsFromPayload');
$parse->setAccessible(true);
$svc = $ref->newInstanceWithoutConstructor();

$obj = (object) [
    'client' => (object) ['email' => 'a', 'subId' => 'x'],
    'inboundIds' => [3, 5, 7],
];
assertTrue('parse inboundIds on root obj', $parse->invoke($svc, $obj) === [3, 5, 7]);

$obj2 = (object) ['client' => (object) ['inboundIds' => [1, 2]]];
assertTrue('parse inboundIds nested', $parse->invoke($svc, $obj2) === [1, 2]);

function isPanelTransientErrorTest($msg): bool
{
    $lower = strtolower($msg);
    return strpos($lower, 'deadlock') !== false
        || strpos($lower, '40p01') !== false
        || strpos($lower, 'missing inbound') !== false;
}

assertTrue('deadlock transient', isPanelTransientErrorTest('deadlock detected'));
assertTrue('missing inbound transient', isPanelTransientErrorTest('Client missing inbound(s): 3'));

echo "\nTotal: $passed passed, $failed failed\n";
exit($failed > 0 ? 1 : 0);
