<?php

namespace App\Http\Controllers;

use App\Models\CollateralAsset;
use App\Services\CoinGeckoService;
use Illuminate\Http\Request;

class CryptoPriceController extends Controller
{
    public function __invoke(CoinGeckoService $coinGeckoService)
    {
        $assets = CollateralAsset::query()
            ->where('is_active', true)
            ->whereNotNull('gecko_id')
            ->get(['symbol', 'gecko_id']);

        $geckoIds = $assets->pluck('gecko_id')->all();
        $prices = $coinGeckoService->getUsdPrices($geckoIds);

        $items = $assets->map(function ($asset) use ($prices) {
            $priceRow = $prices[$asset->gecko_id] ?? null;

            return [
                'symbol' => $asset->symbol,
                'price_usd' => $priceRow['usd'] ?? null,
                'change_24h' => $priceRow['change_24h'] ?? null,
            ];
        })->values();

        return response()->json([
            'items' => $items,
        ]);
    }
}
