<?php

namespace App\Http\Controllers\Api\V1;

use App\Application\Services\Treasury\TreasuryWalletService;
use App\Http\Controllers\Controller;
use App\Models\Asset;
use App\Models\TreasuryWallet;
use App\Models\WalletAddress;
use App\Support\ApiResponse;
use App\Support\AtomicAmount;
use Illuminate\Http\Request;

final class TreasuryWalletController extends Controller
{
    public function index(Request $request)
    {
        $environment = (string) $request->input('environment', config('gateway.environment'));
        $asset = $this->asset($request);

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

        $depositAddresses = WalletAddress::with('invoice')
            ->where('environment', $environment)
            ->where('network', $asset->network)
            ->latest('id')
            ->limit(min(max($request->integer('per_page', 25), 1), 100))
            ->get();

        $totalDepositAtomic = (string) WalletAddress::where('environment', $environment)
            ->where('network', $asset->network)
            ->sum('provider_balance_atomic');

        return ApiResponse::success([
            'environment' => $environment,
            'asset' => [
                'code' => $asset->code,
                'network' => $asset->network,
                'contract_address' => $asset->contract_address,
                'decimals' => $asset->decimals,
            ],
            'main_wallet' => $wallet,
            'deposit_wallets' => [
                'count' => WalletAddress::where('environment', $environment)->where('network', $asset->network)->count(),
                'total_balance_atomic' => $totalDepositAtomic,
                'total_balance' => AtomicAmount::toDecimal($totalDepositAtomic, (int) $asset->decimals),
                'recent' => $depositAddresses->map(fn (WalletAddress $address) => [
                    'id' => $address->id,
                    'invoice_id' => $address->invoice?->public_id,
                    'address' => $address->address,
                    'status' => $address->status,
                    '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(),
                    'last_collected_at' => $address->last_collected_at?->utc()->toIso8601String(),
                ])->values(),
            ],
        ]);
    }

    public function store(Request $request, TreasuryWalletService $service)
    {
        $environment = (string) $request->input('environment', config('gateway.environment'));
        $asset = $this->asset($request);
        $wallet = $service->ensureCollectionWallet($asset, $environment);

        return ApiResponse::success([
            'main_wallet' => $wallet,
            'message' => 'Main collection wallet is ready. Invoice deposit wallets can be swept into this address.',
        ], 201);
    }

    public function sync(Request $request, TreasuryWalletService $service)
    {
        $environment = (string) $request->input('environment', config('gateway.environment'));
        $asset = $this->asset($request);
        $summary = $service->syncDepositAddressBalances($asset, $environment);

        return ApiResponse::success([
            'environment' => $environment,
            'asset_code' => $asset->code,
            ...$summary,
            'total_deposit_balance' => AtomicAmount::toDecimal($summary['total_deposit_balance_atomic'], (int) $asset->decimals),
        ]);
    }

    private function asset(Request $request): Asset
    {
        return Asset::where('code', strtoupper((string) $request->input('asset_code', 'USDTTRC20')))
            ->where('enabled', true)
            ->firstOrFail();
    }
}
