<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\Wallet\WalletTransferReconcileDetector;

final class WalletTransferReconcileCommand extends Command
{
    protected $signature = 'lottery:wallet-transfer-reconcile {--lookback-hours=24 : 回看时间窗口} {--stale-minutes=15 : processing 超过多久算作掉单} {--limit=500 : 每次最多扫描多少笔转账单}';

    protected $description = '扫描主站与彩票侧划转差异，生成钱包对账单';

    public function handle(WalletTransferReconcileDetector $detector): int
    {
        $lookbackHours = max(1, (int) $this->option('lookback-hours'));
        $staleMinutes = max(1, (int) $this->option('stale-minutes'));
        $limit = max(1, (int) $this->option('limit'));

        $job = $detector->scanAndRecord(
            now()->subHours($lookbackHours),
            now(),
            $limit,
            $staleMinutes,
        );

        if ($job === null) {
            $this->info('No wallet transfer discrepancies found.');
            return self::SUCCESS;
        }

        $summary = $job->summary_json ?? [];
        $this->info(sprintf(
            'Created reconcile job %s | items: %d | mismatches: %d',
            $job->job_no,
            (int) ($summary['item_count'] ?? 0),
            (int) ($summary['mismatch_count'] ?? 0),
        ));

        return self::SUCCESS;
    }
}
