<?php

namespace App\Http\Controllers\Api\V1;

use App\Application\Services\Treasury\TreasuryCollectionService;
use App\Http\Controllers\Controller;
use App\Models\AddressCollection;
use App\Models\Asset;
use App\Support\ApiResponse;
use App\Support\AtomicAmount;
use Illuminate\Http\Request;

final class TreasuryCollectionController extends Controller
{
    public function index(Request $request)
    {
        $environment = (string) $request->input('environment', config('gateway.environment'));
        $page = AddressCollection::with(['address.invoice', 'asset'])
            ->where('environment', $environment)
            ->latest('id')
            ->paginate(min(max($request->integer('per_page', 25), 1), 100));

        return ApiResponse::success(
            collect($page->items())->map(fn (AddressCollection $collection) => [
                'id' => $collection->public_id,
                'status' => $collection->status,
                'invoice_id' => $collection->address?->invoice?->public_id,
                'from_address' => $collection->address?->address,
                'asset_code' => $collection->asset?->code,
                'requested_amount_atomic' => (string) $collection->requested_amount_atomic,
                'requested_amount' => $collection->asset ? AtomicAmount::toDecimal((string) $collection->requested_amount_atomic, (int) $collection->asset->decimals) : null,
                'collected_amount_atomic' => (string) $collection->collected_amount_atomic,
                'provider_reference' => $collection->provider_reference,
                'tx_hash' => $collection->tx_hash,
                'failure_reason' => $collection->failure_reason,
                'created_at' => $collection->created_at?->utc()->toIso8601String(),
            ])->values(),
            200,
            ['pagination' => ['page' => $page->currentPage(), 'per_page' => $page->perPage(), 'total' => $page->total(), 'last_page' => $page->lastPage()]]
        );
    }

    public function store(Request $request, TreasuryCollectionService $collections)
    {
        $environment = (string) $request->input('environment', config('gateway.environment'));
        $asset = Asset::where('code', strtoupper((string) $request->input('asset_code', 'USDTTRC20')))
            ->where('enabled', true)
            ->firstOrFail();

        return ApiResponse::success($collections->collectAsset($asset, $environment, $request->integer('limit', 25)), 202);
    }

    public function sync(Request $request, TreasuryCollectionService $collections)
    {
        $environment = (string) $request->input('environment', config('gateway.environment'));

        return ApiResponse::success($collections->syncSubmittedCollections($environment));
    }
}
