<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Checkout\Availability;

use Gls\GlsPoland\Entity\Carrier;
use Gls\GlsPoland\PrestaShop\Configuration\ShopConfigurationRepository;
use Gls\GlsPoland\PrestaShop\ObjectModel\Repository\AddressRepository;
use Gls\GlsPoland\PrestaShop\ObjectModel\Repository\CountryRepository;

final class CountryChecker implements CarrierAvailabilityCheckerInterface
{
    private $addressRepository;
    private $countryRepository;
    private $configuration;

    public function __construct(AddressRepository $addressRepository, CountryRepository $countryRepository, ShopConfigurationRepository $configuration)
    {
        $this->addressRepository = $addressRepository;
        $this->countryRepository = $countryRepository;
        $this->configuration = $configuration;
    }

    public function isAvailable(Carrier $carrier, \Cart $cart): bool
    {
        $country = $this->getDeliveryCountryIsoCode($cart);

        return in_array($country, array_map('strval', $carrier->getCountries()), true);
    }

    private function getDeliveryCountryIsoCode(\Cart $cart): string
    {
        $address = $this->addressRepository->find((int) $cart->id_address_delivery);

        if (
            null === $address ||
            null === $country = $this->countryRepository->find((int) $address->id_country)
        ) {
            $countryId = $this->configuration->getDefaultCountryId();
            $country = $this->countryRepository->find($countryId);
        }

        return $country->iso_code ?? 'PL';
    }
}
