<?php

declare(strict_types=1);

require __DIR__ . '/ExportHarness.php';

$account = (string)getenv('POC_WALLET_ACCOUNT');
if (!preg_match('/^CDXPAY[A-F0-9]{8}$/D', $account)) {
    throw new RuntimeException('Only a named CDXPAY synthetic account may be exported');
}
$h = new ExportHarness('CDXPARSTWEXP');
$staff = ExportHarness::one($h->store,
    'SELECT s.AI_USER_ID,s.NAME FROM ' . $h->s('user') . ' u'
    . ' JOIN ' . $h->s('staff') . ' s ON s.UUID=u.STAFF_UUID WHERE u.ACCOUNT=?',
    [$account]);
if ((int)($staff['ai_user_id'] ?? 0) <= 0 || (string)($staff['name'] ?? '') !== $account) {
    throw new RuntimeException('CDXPAY source staff mapping is not unique');
}
$aiUserId = (int)$staff['ai_user_id'];
$latest = ExportHarness::one($h->ai,
    'SELECT CREATE_TIME FROM ' . $h->a('user_balance_log')
    . ' WHERE USER_ID=? AND STORE_ID=10001 AND MONEY>0 ORDER BY LOG_ID DESC '
    . ($h->dialect === 'dm' ? 'FETCH FIRST 1 ROWS ONLY' : 'LIMIT 1'), [$aiUserId]);
if (!$latest) throw new RuntimeException('No positive CDXPAY cash ledger exists');
$date = date('Y-m-d', (int)$latest['create_time']);
$start = strtotime($date . ' 00:00:00');
$end = strtotime($date . ' 23:59:59');
$query = $h->ai->prepare('SELECT LOG_ID,USER_ID,MONEY,BALANCE_AFTER,CREATE_TIME FROM '
    . $h->a('user_balance_log')
    . ' WHERE USER_ID=? AND STORE_ID=10001 AND MONEY>0 AND CREATE_TIME BETWEEN ? AND ?'
    . ' ORDER BY CREATE_TIME DESC,LOG_ID DESC');
$query->execute([$aiUserId, $start, $end]);
$source = array_map('array_change_key_case', $query->fetchAll(PDO::FETCH_ASSOC));
if (count($source) < 1 || count($source) > 5) {
    throw new RuntimeException('Wallet cash source is not a small bounded test set');
}
$form = ['name' => $account, 'account_type' => 'cash', 'direction' => 'in',
    'start_date' => $date, 'end_date' => $date];
$results = $h->run('/p/walletFlow/export', '/p/walletFlow/exportLogs', 103,
    $form,
    static function (array $conditions) use ($account, $date): bool {
        return ($conditions['name'] ?? null) === $account
            && ($conditions['account_type'] ?? null) === 'cash'
            && trim((string)($conditions['direction'] ?? '')) === 'in'
            && ($conditions['start_date'] ?? null) === $date
            && ($conditions['end_date'] ?? null) === $date;
    },
    static function (array $rows) use ($source, $account): array {
        $n = count($source);
        if (count($rows) !== $n + 3 || count($rows[0]) !== 14
            || ($rows[0]['A'] ?? null) !== '序号'
            || ($rows[0]['B'] ?? null) !== '流水号'
            || ($rows[0]['J'] ?? null) !== '变动金额'
            || ($rows[0]['N'] ?? null) !== '操作人'
            || $rows[$n + 1] !== [] || ($rows[$n + 2]['A'] ?? null) !== '汇总') {
            return ['status' => 'tested-fail', 'reason' => 'wallet-layout'];
        }
        $inflow = '0.00';
        foreach ($source as $index => $item) {
            $row = $rows[$index + 1];
            $money = (string)$item['money'];
            $after = (string)$item['balance_after'];
            $before = bcsub($after, $money, 2);
            if (($row['A'] ?? null) !== (string)($index + 1)
                || ($row['B'] ?? null) !== 'CASH--' . (int)$item['log_id']
                || ($row['C'] ?? null) !== date('Y-m-d H:i:s', (int)$item['create_time'])
                || ($row['D'] ?? null) !== $account
                || ($row['F'] ?? null) !== '现金'
                || ($row['H'] ?? null) !== '入账'
                || bccomp((string)($row['I'] ?? '0'), $before, 2) !== 0
                || bccomp((string)($row['J'] ?? '0'), $money, 2) !== 0
                || bccomp((string)($row['K'] ?? '0'), $after, 2) !== 0) {
                return ['status' => 'tested-fail', 'reason' => 'wallet-source'];
            }
            $inflow = bcadd($inflow, $money, 2);
        }
        $summary = $rows[$n + 2];
        if (($summary['J'] ?? null) !== '总入账：' . $inflow
            || ($summary['K'] ?? null) !== '总出账：0.00'
            || ($summary['L'] ?? null) !== '净变动：' . $inflow) {
            return ['status' => 'tested-fail', 'reason' => 'wallet-summary'];
        }
        return ['status' => 'tested-pass', 'business_rows' => $n,
            'header_columns' => 14,
            'header_sha256' => hash('sha256', json_encode($rows[0], JSON_UNESCAPED_UNICODE)),
            'ledger_money_balance_and_summary_match' => true];
    });
echo json_encode(['dialect' => $h->dialect, 'module' => 'store-wallet-flow-export-type103',
    'results' => $results], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
