<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Checkout\Availability;

use Gls\GlsPoland\DataProvider\ServiceInformationProvider;
use Gls\GlsPoland\Entity\Carrier;
use Gls\GlsPoland\Entity\CourierCarrier;
use Gls\GlsPoland\PrestaShop\Configuration\ShopConfigurationRepository;
use Gls\GlsPoland\PrestaShop\ObjectModel\Repository\CurrencyRepository;

final class CashOnDeliveryChecker implements CarrierAvailabilityCheckerInterface
{
    private $currencyRepository;
    private $configuration;
    private $infoProvider;

    public function __construct(CurrencyRepository $currencyRepository, ShopConfigurationRepository $configuration, ServiceInformationProvider $informationProvider)
    {
        $this->currencyRepository = $currencyRepository;
        $this->configuration = $configuration;
        $this->infoProvider = $informationProvider;
    }

    public function isAvailable(Carrier $carrier, \Cart $cart): bool
    {
        if (!$carrier instanceof CourierCarrier || !$carrier->isCashOnDelivery()) {
            return true;
        }

        if ('PLN' !== $this->getCurrencyIsoCode($cart)) {
            return false;
        }

        $maxCodAmount = $this->infoProvider->getMaxCashOnDeliveryAmount();

        foreach ($cart->getProducts() as $product) {
            if ($maxCodAmount < (float) $product['price_wt']) {
                return false;
            }
        }

        return true;
    }

    private function getCurrencyIsoCode(\Cart $cart): string
    {
        if (null === $currency = $this->currencyRepository->find((int) $cart->id_currency)) {
            $currencyId = $this->configuration->getDefaultCurrencyId();
            $currency = $this->currencyRepository->find($currencyId);
        }

        return $currency->iso_code ?? 'PLN';
    }
}
