<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Checkout;

use Gls\GlsPoland\PrestaShop\Checkout\Availability\CarrierAvailabilityCheckerInterface;
use Gls\GlsPoland\PrestaShop\Helper\CarrierFinder;

final class DeliveryOptionAvailabilityChecker implements DeliveryOptionAvailabilityCheckerInterface
{
    private $carrierFinder;
    private $availabilityCheckers;

    /**
     * @param iterable<CarrierAvailabilityCheckerInterface> $availabilityCheckers
     */
    public function __construct(CarrierFinder $carrierFinder, iterable $availabilityCheckers)
    {
        $this->carrierFinder = $carrierFinder;
        $this->availabilityCheckers = $availabilityCheckers;
    }

    public function isAvailable(int $carrierId, \Cart $cart): bool
    {
        if (null === $carrier = $this->carrierFinder->findOneByCarrierId($carrierId)) {
            return false;
        }

        foreach ($this->availabilityCheckers as $availabilityChecker) {
            assert($availabilityChecker instanceof CarrierAvailabilityCheckerInterface);
            if (!$availabilityChecker->isAvailable($carrier, $cart)) {
                return false;
            }
        }

        return true;
    }
}
