<?php

declare(strict_types=1);

$host = getenv('POC_HOST');
$port = (int)getenv('POC_PORT');
$database = getenv('POC_SCHEMA');
$user = getenv('POC_USER');
$password = getenv('POC_PASSWORD');
$dispatcherFile = getenv('POC_DISPATCHER_FILE');
if (!$host || $port < 1 || !$database || !$user || !$password || !$dispatcherFile || !is_file($dispatcherFile)) exit(2);
require_once $dispatcherFile;

$pdo = new PDO("mysql:host=$host;port=$port;dbname=$database;charset=utf8mb4", $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$table = 'CODEX_DISPATCHER_POC_' . strtoupper(bin2hex(random_bytes(4)));
$pdo->exec('CREATE TEMPORARY TABLE `' . $table . '` ('
    . '`id` INT AUTO_INCREMENT PRIMARY KEY, `biz_type` VARCHAR(32) NOT NULL, `biz_key` VARCHAR(64) NOT NULL, '
    . '`source_id` VARCHAR(64), `detail_snapshot_json` VARCHAR(500), `event_version` INT DEFAULT 1, '
    . '`status` INT DEFAULT 0, `retry_count` INT DEFAULT 0, `next_retry_time` DATETIME, '
    . '`create_by` VARCHAR(36), `create_time` DATETIME, `update_time` DATETIME, `last_error` VARCHAR(500) DEFAULT \'\', '
    . 'UNIQUE KEY `uniq_biz` (`biz_type`,`biz_key`)) ENGINE=InnoDB');

$class = new ReflectionClass(\app\common\service\wanyisheng\Dispatcher::class);
$upsertMethod = $class->getMethod('enqueueSql');
$upsertMethod->setAccessible(true);
$insertMethod = $class->getMethod('insertIfMissingSql');
$insertMethod->setAccessible(true);
$upsert = $pdo->prepare($upsertMethod->invoke(null, $table, false));
$insertOnly = $pdo->prepare($insertMethod->invoke(null, $table, false));
$now = date('Y-m-d H:i:s');

$upsert->execute(['order', 'o1', 'source-1', '{"a":1}', $now, $now, $now]);
$upsert->execute(['order', 'o1', 'source-2', null, $now, $now, $now]);
$row = $pdo->query("SELECT source_id,detail_snapshot_json,event_version,status FROM $table WHERE biz_key='o1'")->fetch(PDO::FETCH_ASSOC);
if ($row['source_id'] !== 'source-2' || $row['detail_snapshot_json'] !== '{"a":1}' || (int)$row['event_version'] !== 2 || (int)$row['status'] !== 0) {
    throw new RuntimeException('MySQL upsert did not preserve regular update behavior');
}

$pdo->exec("UPDATE $table SET status=1,retry_count=4,last_error='retry',next_retry_time='2026-01-01 00:00:00' WHERE biz_key='o1'");
$upsert->execute(['order', 'o1', 'source-3', '{"a":3}', $now, $now, $now]);
$row = $pdo->query("SELECT source_id,detail_snapshot_json,event_version,status,retry_count,last_error,next_retry_time FROM $table WHERE biz_key='o1'")->fetch(PDO::FETCH_ASSOC);
if ($row['source_id'] !== 'source-3' || $row['detail_snapshot_json'] !== '{"a":3}' || (int)$row['event_version'] !== 3
    || (int)$row['status'] !== 1 || (int)$row['retry_count'] !== 4 || $row['last_error'] !== 'retry'
    || strpos((string)$row['next_retry_time'], '2026-01-01') !== 0) {
    throw new RuntimeException('MySQL upsert did not preserve processing-state behavior');
}

$insertOnly->execute(['order', 'o1', 'ignored', $now, $now, $now]);
$matchedAffected = $insertOnly->rowCount();
$insertOnly->execute(['order', 'o2', 'new', $now, $now, $now]);
$insertedAffected = $insertOnly->rowCount();
$count = (int)$pdo->query("SELECT COUNT(*) FROM $table")->fetchColumn();
if ($matchedAffected !== 0 || $insertedAffected !== 1 || $count !== 2) {
    throw new RuntimeException('MySQL insert-if-missing did not preserve ignore-duplicate behavior');
}
echo json_encode(['dialect' => 'mysql', 'upsert' => 'passed', 'processing_state' => 'passed', 'insert_if_missing' => 'passed', 'row_count' => $count]) . PHP_EOL;
