<?php

namespace Webkul\Core\Helpers\Exchange;

use Illuminate\Support\Facades\Http;
use RuntimeException;
use Webkul\Core\Repositories\CurrencyRepository;
use Webkul\Core\Repositories\ExchangeRateRepository;

class ExchangeRates extends ExchangeRate
{
    /**
     * API endpoint.
     */
    protected string $apiEndPoint = 'https://v6.exchangerate-api.com/v6';

    /**
     * API key.
     */
    protected ?string $apiKey;

    /**
     * Create a new instance.
     */
    public function __construct(
        protected CurrencyRepository $currencyRepository,
        protected ExchangeRateRepository $exchangeRateRepository
    ) {
        parent::__construct($currencyRepository, $exchangeRateRepository);

        $this->apiKey = $this->getApiKey(
            'general.exchange_rates.exchange_rates_api.api_key',
            'services.exchange_api.exchange_rates.key'
        );
    }

    /**
     * Fetch rates and update the `currency_exchange_rates` table.
     */
    public function updateRates(): void
    {
        $baseCurrency = config('app.currency');

        $response = Http::get("{$this->apiEndPoint}/{$this->apiKey}/latest/{$baseCurrency}");

        $result = $response->json();

        if ($result['result'] !== 'success') {
            throw new RuntimeException($result['error-type'] ?? 'Unknown error');
        }

        $rates = $result['conversion_rates'];

        foreach ($this->currencyRepository->all() as $currency) {
            if ($currency->code === $baseCurrency) {
                continue;
            }

            if (! isset($rates[$currency->code])) {
                continue;
            }

            $this->updateOrCreateRate($currency, $rates[$currency->code]);
        }
    }
}
