<?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]);
$table = ($dialect === 'dm' ? 'YDY_DISHES' : 'ydy_dishes');
$sql = "SELECT UUID,NAME,PRICE FROM $table WHERE IS_DEL=1 AND STATUS=1 AND UUID IS NOT NULL ORDER BY ID "
    . ($dialect === 'dm' ? 'FETCH FIRST 10 ROWS ONLY' : 'LIMIT 10');
$candidates = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
if (!$candidates) {
    echo json_encode(['dialect' => $dialect, 'status' => 'fixture_missing']) . PHP_EOL;
    exit(3);
}
foreach ($candidates as $candidate) {
    $body = http_build_query(['dishes_uuid' => $candidate['UUID']], '', '&', PHP_QUERY_RFC3986);
    $context = stream_context_create(['http' => [
        'method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
        'content' => $body, 'timeout' => 12, 'ignore_errors' => true,
    ]]);
    $response = file_get_contents(rtrim($url, '/') . '/api/orderMachine/dishDetail', false, $context);
    $data = is_string($response) ? json_decode($response, true) : null;
    if (!is_array($data)) throw new RuntimeException('Dish detail returned non-JSON');
    if (($data['code'] ?? null) !== 0) continue;
    $dish = (array)($data['data'] ?? []);
    if ((string)($dish['uuid'] ?? '') !== (string)$candidate['UUID']
        || (string)($dish['name'] ?? '') !== (string)$candidate['NAME']
        || abs((float)($dish['price'] ?? -1) - (float)$candidate['PRICE']) > 0.001) {
        throw new RuntimeException('Dish detail differs from database');
    }
    echo json_encode(['dialect' => $dialect, 'status' => 'passed',
        'candidate_dishes' => count($candidates), 'uuid_name_price_match_database' => true]) . PHP_EOL;
    exit(0);
}
echo json_encode(['dialect' => $dialect, 'status' => 'no_valid_candidate',
    'candidate_dishes' => count($candidates)]) . PHP_EOL;
exit(1);
