<?php

declare(strict_types=1);

$root = getenv('POC_TARGET_ROOT');
$url = getenv('POC_BASE_URL');
$dialect = getenv('POC_DIALECT');
if (!$root || !$url || !in_array($dialect, ['mysql', 'dm'], true)) exit(2);
$config = require $root . '/application/database.php';
$dsn = $dialect === 'dm'
    ? 'dm:host=' . $config['hostname'] . ';port=' . $config['hostport'] . ';schema=' . $config['database']
    : 'mysql:host=' . $config['hostname'] . ';port=' . $config['hostport'] . ';dbname=' . $config['database'] . ';charset=utf8mb4';
$pdo = new PDO($dsn, $config['username'], $config['password'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$base = rtrim($url, '/');

$post = stream_context_create(['http' => [
    'method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
    'content' => http_build_query(['keyword' => 'CODEXDM8_NO_SUCH_ORDER_20260929']),
    'timeout' => 12, 'ignore_errors' => true,
]]);
$orderBody = file_get_contents($base . '/api/orderMachine/orderList', false, $post);
$order = is_string($orderBody) ? json_decode($orderBody, true) : null;
if (!is_array($order) || ($order['code'] ?? null) !== 0 || (array)($order['data'] ?? [1]) !== []) {
    throw new RuntimeException('Order list empty-boundary query failed');
}

$table = $dialect === 'dm' ? 'YDY_RESTAURANTS' : 'ydy_restaurants';
$sql = "SELECT ID,NAME FROM $table WHERE IS_DELETE=2 AND STATUS=1 ORDER BY ID "
    . ($dialect === 'dm' ? 'FETCH FIRST 30 ROWS ONLY' : 'LIMIT 30');
$candidates = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
$queuePassed = false;
foreach ($candidates as $candidate) {
    $queueBody = file_get_contents($base . '/api/orderMachine/pickupQueue?restaurant_id=' . (int)$candidate['ID']);
    $queue = is_string($queueBody) ? json_decode($queueBody, true) : null;
    if (!is_array($queue)) throw new RuntimeException('Pickup queue returned non-JSON');
    if (($queue['code'] ?? null) !== 0) continue;
    if ((int)($queue['data']['restaurant_id'] ?? 0) !== (int)$candidate['ID']
        || (string)($queue['data']['restaurant_name'] ?? '') !== (string)$candidate['NAME']
        || !is_array($queue['data']['prepare_pickup_nos'] ?? null)
        || !is_array($queue['data']['ready_pickup_nos'] ?? null)) {
        throw new RuntimeException('Pickup queue differs from restaurant database row');
    }
    $queuePassed = true;
    break;
}
echo json_encode(['dialect' => $dialect, 'order_list_empty_boundary' => 'passed',
    'pickup_queue' => $queuePassed ? 'passed' : 'fixture_missing',
    'restaurant_candidates' => count($candidates)]) . PHP_EOL;
exit($queuePassed ? 0 : 3);
