<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Carrier\Configurator;

use InPost\International\Carrier\CarrierConfiguration;
use InPost\International\Carrier\Message\CreateCarrierCommand;
use InPost\International\PrestaShop\ObjectModel\Repository\CountryRepository;
use InPost\International\PrestaShop\ObjectModel\Repository\ObjectRepositoryInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class ZonesConfigurator implements CarrierConfiguratorInterface
{
    /**
     * @var CountryRepository
     */
    private $countryRepository;

    /**
     * @param CountryRepository $countryRepository
     */
    public function __construct(ObjectRepositoryInterface $countryRepository)
    {
        $this->countryRepository = $countryRepository;
    }

    public function configure(CarrierConfiguration $configuration, CreateCarrierCommand $command): void
    {
        foreach ($command->getCountries() as $country) {
            if (null === $zoneId = $this->getZoneIdByCountryCode($country->value)) {
                continue;
            }

            $configuration->addZone($zoneId);
        }
    }

    private function getZoneIdByCountryCode(string $isoCode): ?int
    {
        if (null === $country = $this->countryRepository->findOneByIsoCode($isoCode)) {
            return null;
        }

        if (0 >= $zoneId = (int) $country->id_zone) {
            return null;
        }

        return $zoneId;
    }
}
