<?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\Configuration\MessageHandler;

use InPost\International\Configuration\CheckoutConfiguration;
use InPost\International\Configuration\Message\UpdateCheckoutConfigurationCommand;
use InPost\International\Configuration\Repository\CheckoutConfigurationRepositoryInterface;
use InPost\International\Configuration\Repository\GeocodingConfigurationRepositoryInterface;

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

final class UpdateCheckoutConfigurationHandler
{
    /**
     * @var CheckoutConfigurationRepositoryInterface
     */
    private $checkoutConfigRepository;

    /**
     * @var GeocodingConfigurationRepositoryInterface
     */
    private $geocodingConfigRepository;

    public function __construct(CheckoutConfigurationRepositoryInterface $checkoutConfigRepository, GeocodingConfigurationRepositoryInterface $geocodingConfigRepository)
    {
        $this->checkoutConfigRepository = $checkoutConfigRepository;
        $this->geocodingConfigRepository = $geocodingConfigRepository;
    }

    public function __invoke(UpdateCheckoutConfigurationCommand $command): void
    {
        $this->updateCheckoutConfig($command);
        $this->updateGeocodingConfig($command);
    }

    public function handle(UpdateCheckoutConfigurationCommand $command): void
    {
        ($this)($command);
    }

    private function updateCheckoutConfig(UpdateCheckoutConfigurationCommand $command): void
    {
        $configuration = new CheckoutConfiguration($command->getClosestPointSerachMode());

        $this->checkoutConfigRepository->saveCheckoutConfiguration($configuration);
    }

    private function updateGeocodingConfig(UpdateCheckoutConfigurationCommand $command): void
    {
        foreach ($command->getGeocoderConfigs() as $type => $config) {
            if (null === $config) {
                $this->geocodingConfigRepository->removeGeocoderOptions($type);
            } else {
                $this->geocodingConfigRepository->saveGeocoderOptions($type, $config->toArray());
            }
        }
    }
}
