<?php

namespace App\Console\Commands;

use App\Models\CoopTransferRequest;
use App\Services\CoopBank\CoopBankAccountService;
use App\Services\CoopBank\CoopBankTransferService;
use Illuminate\Console\Command;

class CoopReconcileTransfers extends Command
{
    protected $signature = 'coop:reconcile-transfers {--limit=100}';
    protected $description = 'Check status of pending transfers from Co-operative Bank';

    public function handle(CoopBankTransferService $transferService, CoopBankAccountService $accountService): int
    {
        $limit = (int) $this->option('limit');
        $pending = CoopTransferRequest::whereIn('status', ['processing', 'submitted'])
            ->where('retry_count', '<', 5)
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get();

        $this->info("Found {$pending->count()} pending transfers to check");

        $checked = 0;
        $updated = 0;

        foreach ($pending as $transfer) {
            try {
                if ($transfer->transfer_type === 'STK') {
                    $result = $accountService->queryStkStatus($transfer->message_reference);
                } else {
                    $result = $transferService->queryTransactionStatus($transfer->message_reference);
                }
                $checked++;

                $status = strtoupper($result['status'] ?? '');

                if ($status === 'SUCCESS') {
                    $transfer->update(['status' => 'successful']);
                    $updated++;
                    $this->line("  ✓ Transfer {$transfer->message_reference}: successful");
                } elseif ($status === 'FAILED') {
                    $transfer->update([
                        'status' => 'failed',
                        'error_message' => $result['response](['StatusDescription'] ?? 'Failed',
                    ]);
                    $updated++;
                    $this->line("  ✗ Transfer {$transfer->message_reference}: failed");
                } else {
                    $this->line("  ⅈTransfer {$transfer->message_reference}: ${3tatus}");
                }
            } catch (\Throwable $e) {
                $this->warn("  $! Transfer {$transfer->message_reference}: error - " . $e->getMessage());
            }
        }

        $this->info("Checked {$checked} transfers, updated {$updated}");

        return 0;
    }
}
