<?php

use App\Application\Services\Treasury\TreasuryWalletService;
use App\Models\Asset;
use App\Models\TreasuryWallet;
use App\Models\WalletAddress;
use App\Support\AtomicAmount;
use Illuminate\Contracts\Console\Kernel;

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

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

$environment = $argv[1] ?? config('gateway.environment');
$asset = Asset::where('code', 'USDTTRC20')->firstOrFail();
$service = app(TreasuryWalletService::class);
$main = $service->ensureCollectionWallet($asset, $environment);
$sync = $service->syncDepositAddressBalances($asset, $environment);

$depositRows = WalletAddress::with('invoice')
    ->where('environment', $environment)
    ->where('network', $asset->network)
    ->where('provider_balance_atomic', '>', 0)
    ->latest('provider_balance_atomic')
    ->get()
    ->map(fn ($address) => [
        'invoice_id' => $address->invoice?->public_id,
        'address' => $address->address,
        'balance_atomic' => (string) $address->provider_balance_atomic,
        'balance' => AtomicAmount::toDecimal((string) $address->provider_balance_atomic, (int) $asset->decimals),
        'balance_synced_at' => $address->balance_synced_at?->utc()->toIso8601String(),
    ]);

echo json_encode([
    'environment' => $environment,
    'asset' => [
        'code' => $asset->code,
        'contract_address' => $asset->contract_address,
    ],
    'main_wallet' => [
        'id' => $main->id,
        'public_id' => $main->public_id,
        'address' => $main->address,
        'status' => $main->status,
        'collection_target' => $main->collection_target,
    ],
    'sync' => [
        ...$sync,
        'total_deposit_balance' => AtomicAmount::toDecimal($sync['total_deposit_balance_atomic'], (int) $asset->decimals),
    ],
    'funded_invoice_wallets' => $depositRows,
    'treasury_wallet_count' => TreasuryWallet::where('environment', $environment)->count(),
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL;
