<?php

namespace App\Console\Commands;

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

class CollectSyncMember extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'collect:sync-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::syncMemberCollectRecords($memberId);
        if (empty($result['success'])) {
            $this->error($result['message'] ?? '处理失败');
            return Command::FAILURE;
        }

        $this->table(
            ['member_id', 'recharge_count', 'processed_count', 'created_count', 'updated_count', 'skipped_count', 'failed_count'],
            [[
                $result['member_id'],
                $result['recharge_count'],
                $result['processed_count'],
                $result['created_count'],
                $result['updated_count'],
                $result['skipped_count'],
                $result['failed_count'],
            ]]
        );

        if (!empty($result['items'])) {
            $this->table(
                ['from_address', 'action', 'collect_id', 'amount', 'recharge_txid', 'error'],
                array_map(function ($item) {
                    return [
                        $item['from_address'],
                        $item['action'],
                        $item['collect_id'],
                        $item['amount'],
                        $item['recharge_txid'],
                        $item['error'],
                    ];
                }, $result['items'])
            );
        }

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