<?php

namespace App\Console\Commands;

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

class CollectExecuteMember extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'collect:execute-member {member_id : 用户 member_id}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '按指定用户执行待归集记录的链上归集';

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

        $this->info("开始执行用户 {$memberId} 的归集...");

        $result = CollectService::syncCollectStayByMember($memberId);
        if (($result['handled_count'] ?? 0) === 0 && !empty($result['message'])) {
            $this->error($result['message']);
            return Command::FAILURE;
        }

        $this->table(
            ['member_id', 'from_address', 'to_address', 'pending_count', 'handled_count', 'success_count', 'fail_count'],
            [[
                $result['member_id'] ?? $memberId,
                $result['from_address'] ?? '',
                $result['to_address'] ?? '',
                $result['pending_count'] ?? 0,
                $result['handled_count'] ?? 0,
                $result['success_count'] ?? 0,
                $result['fail_count'] ?? 0,
            ]]
        );

        if (!empty($result['items'])) {
            $this->table(
                ['id', 'from_address', 'amount', 'status', 'txid', 'error'],
                array_map(function ($item) {
                    return [
                        $item['id'] ?? null,
                        $item['from_address'] ?? '',
                        $item['amount'] ?? '',
                        $item['status'] ?? '',
                        $item['txid'] ?? '',
                        $item['error'] ?? '',
                    ];
                }, $result['items'])
            );
        }

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