<?php
declare(strict_types=1);
require_once __DIR__ . '/scenarios.php';
$checks = 0;
function check(bool $condition, string $message): void { global $checks; $checks++; if (!$condition) { throw new RuntimeException($message); } }
$safe = runScenario('stock','fixed'); $broken = runScenario('stock','broken');
check($safe['snapshot']['orders'] === 1 && $safe['snapshot']['stock'] === 0, 'Last-item invariant');
check($broken['snapshot']['orders'] === 2, 'Controlled stale-read reproduction');
$retry = runScenario('retry','fixed'); check($retry['detail'][1]['replayed'] && $retry['snapshot']['events'] === 1, 'Retry identity');
$rollback = runScenario('rollback','fixed'); check($rollback['detail']['afterFailure'] === ['stock'=>1,'orders'=>0,'events'=>0,'receipts'=>0], 'Full rollback');
check($rollback['snapshot']['orders'] === 1, 'Retry after rollback');
$delivery = runScenario('delivery','fixed'); check($delivery['snapshot']['receipts'] === 1 && !$delivery['detail']['redelivery'], 'Local receiver deduplication');
check(runScenario('delivery','broken')['snapshot']['receipts'] === 2, 'Repeated-attempt reproduction');
$before = runScenario('query','broken'); $after = runScenario('query','fixed');
check($before['detail']['ids'] === $after['detail']['ids'], 'Equal query results');
check(str_contains(json_encode($after['detail']['plan']), 'history_customer_status_recent'), 'Index appears in actual plan');
$store = OrderStore::fixture(); $store->reserve('request-001');
try { $store->reserve('request-001',2); check(false,'Changed retry body accepted'); } catch (DomainException) { check(true,'Changed body rejected'); }
check($store->snapshot()['orders'] === 1, 'Changed body leaves state untouched');
foreach (['', 'short', 'https://bad.test/'] as $key) { try { $store->reserve($key); check(false,'Invalid key accepted'); } catch (InvalidArgumentException) { check(true,'Key validation'); } }
try { runScenario('unknown','fixed'); check(false,'Unknown scenario accepted'); } catch (InvalidArgumentException) { check(true,'Scenario validation'); }
try { $store->deliver('unknown'); check(false,'Unknown event accepted'); } catch (InvalidArgumentException) { check(true,'Event validation'); }
echo json_encode(['checks'=>$checks,'status'=>'passed','runtime'=>PHP_VERSION], JSON_PRETTY_PRINT), PHP_EOL;
