<?php

use App\Domain\Blockchain\Contracts\BlockchainGateway;
use App\Jobs\FinalizePaymentJob;
use App\Models\Invoice;
use Illuminate\Contracts\Console\Kernel;

require __DIR__.'/../../vendor/autoload.php';

$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();

$publicId = $argv[1] ?? '';
$invoice = Invoice::with(['invoiceTransactions.chainTransaction', 'asset'])
    ->where('public_id', $publicId)
    ->first();

if (! $invoice) {
    fwrite(STDERR, "Invoice not found: {$publicId}\n");
    exit(1);
}

$gateway = app(BlockchainGateway::class);

foreach ($invoice->invoiceTransactions as $link) {
    $tx = $link->chainTransaction;
    if (! $tx) {
        continue;
    }

    $fresh = $gateway->getTransaction($tx->network, $tx->tx_hash);
    $tx->update([
        'confirmations' => $fresh->confirmations,
        'finality_status' => $fresh->status,
        'block_height' => $fresh->blockHeight,
    ]);
}

(new FinalizePaymentJob($invoice->id))->handle(
    app(App\Application\Services\Blockchain\PaymentFinalizer::class)
);

echo "Finality refreshed and finalize attempted for {$publicId}\n";
