<?php

declare(strict_types=1);

$lane = $argv[1] ?? '';
if (!in_array($lane, ['B', 'C'], true)) exit(2);
$root = '/tmp/cdx-prepay-code-scan-20261012-' . $lane . '-store';
$dialect = $lane === 'B' ? 'mysql' : 'dm';
$marker = $lane === 'B' ? 'CDXPPREF12B01' : 'CDXPPREF12C01';
$staffUuid = $marker . '-ST';
$userUuid = 'CDXUSER-' . $marker;
$deviceId = $lane === 'B' ? 232 : 178;
$pid = (int)file_get_contents($root . '/private-http.pid');
if (strpos((string)file_get_contents('/proc/' . $pid . '/cmdline'), $root . '/public') === false) {
    throw new RuntimeException('Wrong private Store owner');
}
foreach (explode("\0", (string)file_get_contents('/proc/' . $pid . '/environ')) as $pair) {
    $parts = explode('=', $pair, 2);
    if (count($parts) === 2 && strpos($parts[0], 'POC_') === 0) putenv($pair);
}
if (getenv('POC_DIALECT') !== $dialect) throw new RuntimeException('Wrong test DB dialect');
$cfg = require $root . '/application/database.php';
$connect = static function (array $c) use ($dialect): PDO {
    $dsn = $dialect === 'dm'
        ? 'dm:host=' . $c['hostname'] . ';port=' . $c['hostport'] . ';schema=' . $c['database']
        : 'mysql:host=' . $c['hostname'] . ';port=' . ($c['hostport'] ?? 3306)
            . ';dbname=' . $c['database'] . ';charset=utf8mb4';
    return new PDO($dsn, $c['username'], $c['password'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
};
$store = $connect($cfg);
$ai = $connect($cfg['ai_zhct']);
$table = static function (string $name, bool $isAi = false) use ($dialect): string {
    $prefix = $isAi ? 'yoshop_' : 'ydy_';
    return $dialect === 'dm' ? strtoupper($prefix . $name) : $prefix . $name;
};
$all = static function (PDO $db, string $sql, array $params = []): array {
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    return array_map(static function (array $row): array {
        return array_change_key_case($row, CASE_LOWER);
    }, $stmt->fetchAll(PDO::FETCH_ASSOC));
};
$mainSource = (string)file_get_contents($root . '/application/common.php');
$rechargeSource = (string)file_get_contents($root . '/application/common/service/account/GiftRechargeService.php');
if (strpos($mainSource, '$store_id = 10001;') === false
    || strpos($rechargeSource, "'store_id' => " . '$storeId') === false) {
    throw new RuntimeException('Store tenant source contract changed');
}
$storeTenant = $all($ai, 'SELECT STORE_ID,IS_DELETE,IS_RECYCLE FROM '
    . $table('store', true) . ' WHERE STORE_ID=?', [10001]);
$device = $all($store, 'SELECT ID,CODE,SN,RESTAURANT_ID,TYPE,DEL_FLAG,STATUS FROM '
    . $table('equipment') . ' WHERE ID=?', [$deviceId]);
if (count($storeTenant) !== 1 || (int)$storeTenant[0]['is_delete'] !== 0
    || (int)$storeTenant[0]['is_recycle'] !== 0 || count($device) !== 1
    || (int)$device[0]['type'] !== 60 || (int)$device[0]['del_flag'] !== 0
    || (int)$device[0]['status'] !== 2 || (string)$device[0]['sn'] !== 'CDXPPFORM11_M1') {
    throw new RuntimeException('Actual store10001 or owned device unavailable');
}
$restaurant = $all($store, 'SELECT ID,STALL_TYPE FROM '
    . $table('restaurants') . ' WHERE ID=?', [(int)$device[0]['restaurant_id']]);
if (count($restaurant) !== 1 || (int)$restaurant[0]['stall_type'] !== 1) {
    throw new RuntimeException('Owned restaurant not safe type1');
}
$existing = [
    'ai_user' => $all($ai, 'SELECT USER_ID FROM ' . $table('user', true)
        . ' WHERE NICK_NAME=? AND STORE_ID=?', [$marker, 10001]),
    'staff' => $all($store, 'SELECT ID FROM ' . $table('staff')
        . ' WHERE UUID=?', [$staffUuid]),
    'store_user' => $all($store, 'SELECT ID FROM ' . $table('user')
        . ' WHERE ACCOUNT=?', [$marker]),
];
foreach ($existing as $rows) if ($rows) throw new RuntimeException('New marker already exists');
if (getenv('POC_DRY_RUN') === '1') {
    echo json_encode(['lane' => $lane, 'marker' => $marker,
        'store_id_source' => 10001, 'ai_store_10001_active' => true,
        'device_id' => $deviceId, 'restaurant_id' => (int)$restaurant[0]['id'],
        'restaurant_stall_type' => 1,
        'new_identity_rows' => [0, 0, 0], 'DML' => 0]) . PHP_EOL;
    exit(0);
}
$attemptPath = $root . '/fixture10001-attempt.json';
if (is_file($attemptPath)) throw new RuntimeException('Fixture creation already attempted');
$handle = fopen($attemptPath, 'xb');
if (!$handle) throw new RuntimeException('Cannot lock fixture creation');
fwrite($handle, json_encode(['lane' => $lane, 'marker' => $marker,
    'store_id' => 10001, 'at' => date('c')]));
fclose($handle);
chmod($attemptPath, 0600);
$now = date('Y-m-d H:i:s');
$aiId = 0;
$staffId = 0;
$userId = 0;
$ai->beginTransaction();
$store->beginTransaction();
$committed = false;
try {
    $stmt = $ai->prepare('INSERT INTO ' . $table('user', true)
        . ' (STORE_ID,MOBILE,NICK_NAME,BALANCE,GIFT_BALANCE,IS_DELETE,CREATE_TIME)'
        . ' VALUES (?,?,?,?,?,?,?)');
    $stmt->execute([10001, '', $marker, '0.00', '0.00', 0, time()]);
    $aiRows = $all($ai, 'SELECT USER_ID FROM ' . $table('user', true)
        . ' WHERE NICK_NAME=? AND STORE_ID=?', [$marker, 10001]);
    if (count($aiRows) !== 1) throw new RuntimeException('AI synthetic identity not unique');
    $aiId = (int)$aiRows[0]['user_id'];

    $stmt = $store->prepare('INSERT INTO ' . $table('staff')
        . ' (UUID,STATION_UUID,NAME,BIRTHDAY,SPORT_UUID,SPORT_EVENT_UUID,IN_TIME,'
        . 'CREATE_TIME,CREATE_BY,PERSONNEL_UMBER,PERMANENT_ADDRESS,COACH_NAME,SPORT_YEAR,'
        . 'IS_SHOW,AI_USER_ID,JOB_STATUS) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
    $stmt->execute([$staffUuid, $marker . '-STATION', $marker, '1990-01-01',
        $marker . '-SPORT', '[]', date('Y-m-d'), $now, $marker, $marker,
        'CDX TEST', 'CDX TEST', '0', 1, $aiId, 1]);
    $staffRows = $all($store, 'SELECT ID FROM ' . $table('staff')
        . ' WHERE UUID=?', [$staffUuid]);
    if (count($staffRows) !== 1) throw new RuntimeException('Store staff not unique');
    $staffId = (int)$staffRows[0]['id'];

    $stmt = $store->prepare('INSERT INTO ' . $table('user')
        . ' (UUID,STAFF_UUID,AI_USER_ID,ACCOUNT,PWD,SALT,NAME,CREATE_TIME,CREATE_BY,IS_DELETE)'
        . ' VALUES (?,?,?,?,?,?,?,?,?,?)');
    $stmt->execute([$userUuid, $staffUuid, $aiId, $marker, 'DISABLED',
        strtoupper(bin2hex(random_bytes(8))), $marker, $now, $marker, 0]);
    $userRows = $all($store, 'SELECT ID FROM ' . $table('user')
        . ' WHERE ACCOUNT=?', [$marker]);
    if (count($userRows) !== 1) throw new RuntimeException('Store user not unique');
    $userId = (int)$userRows[0]['id'];
    if (min($aiId, $staffId, $userId) <= 0) throw new RuntimeException('Identity not positive');
    $ai->commit();
    $store->commit();
    $committed = true;
} finally {
    if (!$committed) {
        if ($ai->inTransaction()) $ai->rollBack();
        if ($store->inTransaction()) $store->rollBack();
    }
}
$aiVerify = $all($ai, 'SELECT USER_ID,STORE_ID,IS_DELETE,BALANCE,GIFT_BALANCE FROM '
    . $table('user', true) . ' WHERE USER_ID=?', [$aiId]);
$staffVerify = $all($store, 'SELECT ID,UUID,AI_USER_ID,JOB_STATUS,IS_SHOW FROM '
    . $table('staff') . ' WHERE ID=?', [$staffId]);
$userVerify = $all($store, 'SELECT ID,UUID,STAFF_UUID,AI_USER_ID,ACCOUNT,IS_DELETE FROM '
    . $table('user') . ' WHERE ID=?', [$userId]);
$receipt = ['lane' => $lane, 'marker' => $marker,
    'store_id' => 10001, 'ai_user_id' => $aiId,
    'staff_id' => $staffId, 'store_user_id' => $userId,
    'ai_rows' => count($aiVerify), 'staff_rows' => count($staffVerify),
    'store_user_rows' => count($userVerify),
    'linked_ids_match' => count($staffVerify) === 1 && count($userVerify) === 1
        && (int)$staffVerify[0]['ai_user_id'] === $aiId
        && (int)$userVerify[0]['ai_user_id'] === $aiId
        && (string)$userVerify[0]['staff_uuid'] === $staffUuid,
    'ai_tenant_correct' => count($aiVerify) === 1
        && (int)$aiVerify[0]['store_id'] === 10001,
    'initial_cash_zero' => count($aiVerify) === 1
        && bccomp((string)$aiVerify[0]['balance'], '0.00', 2) === 0,
    'staff_eligible' => count($staffVerify) === 1
        && (int)$staffVerify[0]['job_status'] === 1
        && (int)$staffVerify[0]['is_show'] === 1];
$receipt['passed'] = $receipt['ai_rows'] === 1
    && $receipt['staff_rows'] === 1 && $receipt['store_user_rows'] === 1
    && $receipt['linked_ids_match'] && $receipt['ai_tenant_correct']
    && $receipt['initial_cash_zero'] && $receipt['staff_eligible'];
file_put_contents($root . '/fixture10001-receipt.json', json_encode($receipt,
    JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), LOCK_EX);
chmod($root . '/fixture10001-receipt.json', 0600);
echo json_encode($receipt, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
exit($receipt['passed'] ? 0 : 1);
