<?php

namespace App\Application\Services;

use App\Models\Asset;
use App\Support\AtomicAmount;
use RuntimeException;

final class QuoteService
{
    public function quote(string $priceAmount, string $priceCurrency, Asset $asset): array
    {
        if (strtoupper($priceCurrency) !== 'USD' || strtoupper($asset->code) !== 'USDTTRC20') {
            throw new RuntimeException('UNSUPPORTED_CURRENCY');
        }
        if (!function_exists('bcmul')) throw new RuntimeException('BCMATH_REQUIRED');
        $baseRate = (string) config('gateway.rates.usdt_usd_rate', '1.00000000');
        $markupBps = (int) config('gateway.rates.markup_bps', 0);
        $multiplier = bcadd('1', bcdiv((string) $markupBps, '10000', 12), 12);
        $rate = bcmul($baseRate, $multiplier, 12);
        $payAmount = bcmul($priceAmount, $rate, $asset->decimals);
        $atomic = AtomicAmount::fromDecimal($payAmount, $asset->decimals);
        return [
            'rate' => $rate,
            'amount_atomic' => $atomic,
            'amount' => AtomicAmount::toDecimal($atomic, $asset->decimals),
            'expires_at' => now()->addSeconds((int) config('gateway.rates.ttl_seconds', 60)),
            'source' => 'internal_fixed_rate',
        ];
    }
}
