<?php

use App\Models\Asset;
use App\Models\TreasuryWallet;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Str;

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

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

$address = $argv[1] ?? '';
$environment = $argv[2] ?? config('gateway.environment');
$assetCode = $argv[3] ?? 'USDTTRC20';

if ($address === '') {
    fwrite(STDERR, "Usage: php storage/app/set_main_treasury_wallet.php <address> [environment] [asset_code]\n");
    exit(1);
}

$asset = Asset::where('code', strtoupper($assetCode))->firstOrFail();

$existing = TreasuryWallet::whereNull('merchant_id')
    ->where('asset_id', $asset->id)
    ->where('environment', $environment)
    ->where('collection_target', true)
    ->first();

$wallet = TreasuryWallet::updateOrCreate(
    [
        'merchant_id' => null,
        'asset_id' => $asset->id,
        'environment' => $environment,
        'collection_target' => true,
    ],
    [
        'public_id' => $existing?->public_id ?? 'tw_'.Str::ulid(),
        'provider_wallet_id' => 'external-main-hot-wallet',
        'address' => $address,
        'status' => 'active',
        'policy' => [
            'role' => 'main_collection_wallet',
            'network' => $asset->network,
            'asset_code' => $asset->code,
            'managed_by' => 'operator',
        ],
    ]
);

echo json_encode([
    'main_wallet' => [
        'id' => $wallet->id,
        'public_id' => $wallet->public_id,
        'address' => $wallet->address,
        'environment' => $wallet->environment,
        'asset_code' => $asset->code,
        'collection_target' => $wallet->collection_target,
        'status' => $wallet->status,
    ],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL;
