<?php

namespace App\Console\Commands;

use App\Services\RechargeService;
use Illuminate\Console\Command;

class RechargeSyncMember extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'recharge:sync-member {member_id : 用户 member_id} {--confirm-only : 只确认已有待确认记录，不重新拉链上充值}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '按指定用户重新同步并确认 USDT 自动充值';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $memberId = $this->argument('member_id');
        $confirmOnly = (bool) $this->option('confirm-only');

        $this->info("开始处理用户 {$memberId} 的充值记录...");

        $result = RechargeService::syncAndConfirmMemberRecharge($memberId, !$confirmOnly, true);
        if (empty($result['success'])) {
            $this->error($result['message'] ?? '处理失败');
            return Command::FAILURE;
        }

        $this->table(
            ['member_id', 'address', 'synced', 'checked', 'confirmed', 'remaining_pending', 'collect_ensured'],
            [[
                $result['member_id'],
                $result['address'],
                $result['synced'],
                $result['checked'],
                $result['confirmed'],
                $result['remaining_pending'],
                $result['collect_ensured'],
            ]]
        );

        if (!empty($result['confirmed_txids'])) {
            $this->line('已确认交易:');
            foreach ($result['confirmed_txids'] as $txid) {
                $this->line($txid);
            }
        }

        if (!empty($result['collect_addresses'])) {
            $this->line('已补建待归集地址:');
            foreach ($result['collect_addresses'] as $address) {
                $this->line($address);
            }
        }

        $this->info('处理完成');
        return Command::SUCCESS;
    }
}
