<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonShippingCommon\Components;

use Shopware\Components\Model\ModelRepository;
use Shopware\Models\Shop\Currency;
use Shopware\Plugins\ViisonShippingCommon\Classes\Exceptions\CurrencyConverterException;

class CurrencyConverter
{
    /**
     * @var ModelRepository
     */
    private $currencyRepository;

    public function __construct(ModelRepository $currencyRepository)
    {
        $this->currencyRepository = $currencyRepository;
    }

    /**
     * Calculate the conversion factor for a given currency to another.
     *
     * @param string $currencyIsoCodeToConvertFrom
     * @param string $currencyIsoCodeToConvertTo
     * @return float|int
     * @throws CurrencyConverterException
     */
    public function getConversionFactor($currencyIsoCodeToConvertFrom, $currencyIsoCodeToConvertTo)
    {
        if ($currencyIsoCodeToConvertFrom === $currencyIsoCodeToConvertTo) {
            return 1;
        }

        /** @var Currency $currencyToConvertFrom */
        $currencyToConvertFrom = $this->currencyRepository->findOneBy([
            'currency' => $currencyIsoCodeToConvertFrom,
        ]);
        if (!$currencyToConvertFrom || $currencyToConvertFrom->getFactor() === 0.0) {
            throw CurrencyConverterException::currencyFactorNotConfigured($currencyIsoCodeToConvertFrom);
        }
        /** @var Currency $currencyToConvertTo */
        $currencyToConvertTo = $this->currencyRepository->findOneBy([
            'currency' => $currencyIsoCodeToConvertTo,
        ]);
        if (!$currencyToConvertTo || $currencyToConvertTo->getFactor() === 0.0) {
            throw CurrencyConverterException::currencyFactorNotConfigured($currencyIsoCodeToConvertTo);
        }

        return $currencyToConvertTo->getFactor() / $currencyToConvertFrom->getFactor();
    }
}
