<?php

declare(strict_types=1);

require '/workspace/zhct/zhctproject/store/tests/bootstrap.php';
require_once '/workspace/zhct/zhctproject/store/thinkphp/helper.php';

\think\Config::set(require APP_PATH . 'database.php', 'database');
$aiDb = get_ai_db();
$database = (string)$aiDb->query('SELECT DATABASE() AS database_name')[0]['database_name'];
if (TP_ENV !== 'local' || $database !== 'ai_zhct') {
    throw new RuntimeException('Only the local ai_zhct development database is allowed');
}

$staffUuid = trim((string)($argv[1] ?? ''));
$marker = trim((string)($argv[2] ?? ''));
$amount = (string)($argv[3] ?? '0.01');
if ($staffUuid === '' || strpos($marker, 'VWCG-1381-CONCURRENT-') !== 0) {
    throw new InvalidArgumentException('Invalid persistent test fixture');
}

$staff = \think\Db::name('staff')->where('uuid', $staffUuid)
    ->where('name', 'like', 'VWCG-1381-CONCURRENT-%')
    ->where('is_show', 1)
    ->field('uuid,ai_user_id')
    ->find();
if (!$staff) {
    throw new RuntimeException('Persistent test staff not found');
}

$result = (new \app\p\logic\RechargeOrder())->add(
    '',
    $staffUuid,
    $amount,
    \app\common\enum\payment\Method::CASH,
    $marker,
    'Codex并发测试'
);
if ((int)($result['code'] ?? 1) !== 0) {
    throw new RuntimeException('Recharge failed: ' . json_encode($result, JSON_UNESCAPED_UNICODE));
}

$order = $aiDb->name('recharge_order')->where('user_id', (int)$staff['ai_user_id'])
    ->where('note', $marker)->order('order_id', 'desc')->find();
$log = $order ? $aiDb->name('user_balance_log')
    ->where('order_id', (int)$order['order_id'])
    ->where('scene', 30)
    ->find() : null;
if (!$order || !$log || $log['balance_after'] === null) {
    throw new RuntimeException('Recharge ledger was not persisted completely');
}

echo json_encode([
    'database' => $database,
    'staff_uuid' => $staffUuid,
    'ai_user_id' => (int)$staff['ai_user_id'],
    'order_id' => (int)$order['order_id'],
    'order_no' => (string)$order['order_no'],
    'money' => (string)$log['money'],
    'balance_after' => (string)$log['balance_after'],
    'marker' => $marker,
], JSON_UNESCAPED_UNICODE) . PHP_EOL;
