<?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\ObjectModel\Repository\AddressRepository;

final class ExpressDeliveryChecker implements CarrierAvailabilityCheckerInterface
{
    private $addressRepository;
    private $infoProvider;

    public function __construct(AddressRepository $addressRepository, ServiceInformationProvider $informationProvider)
    {
        $this->addressRepository = $addressRepository;
        $this->infoProvider = $informationProvider;
    }

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

        $address = $this->addressRepository->find((int) $cart->id_address_delivery);

        if (null === $address || '' === $zipCode = trim($address->postcode ?? '')) {
            return false;
        }

        if (null === $services = $this->infoProvider->getGuaranteedServices($zipCode)) {
            return false;
        }

        return (!$carrier->isDeliveryBefore10() || $services->isDeliveryBefore10())
            && (!$carrier->isDeliveryBefore12() || $services->isDeliveryBefore12())
            && (!$carrier->isSaturdayDelivery() || $services->isSaturdayDelivery());
    }
}
