<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Http;
use Throwable;

/**
 * Units of a currency per 1 USD, as last fetched.
 *
 * Only the stored value is ever read by the ceiling, so a failed fetch leaves
 * the previous rate in force rather than removing the limit.
 */
class ExchangeRate extends Model
{
    public $incrementing = false;

    protected $primaryKey = 'currency';

    protected $keyType = 'string';

    protected $fillable = ['currency', 'rate_per_usd', 'fetched_at'];

    protected function casts(): array
    {
        return ['rate_per_usd' => 'float', 'fetched_at' => 'datetime'];
    }

    public static function perUsd(string $currency): ?float
    {
        $rate = static::query()->whereKey(strtoupper($currency))->value('rate_per_usd');

        return $rate !== null && (float) $rate > 0 ? (float) $rate : null;
    }

    /** Fetch and store the latest rates. Returns how many were stored, 0 on failure. */
    public static function fetchLatest(): int
    {
        try {
            $response = Http::timeout(10)->get(config('platforms.guardrails.fx.url'), ['base' => 'USD']);
            $rates = $response->successful() ? $response->json('rates') : null;
        } catch (Throwable $e) {
            report($e);

            return 0;
        }

        if (! is_array($rates)) {
            return 0;
        }

        $stored = 0;

        foreach ($rates as $currency => $rate) {
            if (! is_numeric($rate) || (float) $rate <= 0) {
                continue;
            }

            static::query()->updateOrCreate(
                ['currency' => strtoupper((string) $currency)],
                ['rate_per_usd' => $rate, 'fetched_at' => now()],
            );
            $stored++;
        }

        return $stored;
    }
}
