<?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\Message\UpdateApiConfigurationCommand;
use InPost\International\Configuration\Repository\ApiConfigurationRepositoryInterface;

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

final class UpdateApiConfigurationHandler
{
    /**
     * @var ApiConfigurationRepositoryInterface
     */
    private $repository;

    public function __construct(ApiConfigurationRepositoryInterface $repository)
    {
        $this->repository = $repository;
    }

    public function __invoke(UpdateApiConfigurationCommand $command): void
    {
        if (null === $environment = $command->getEnvironment()) {
            throw new \DomainException('Environment is required.');
        }

        foreach ($command->getConfigurations() as $configuration) {
            $this->repository->saveConfiguration($configuration);
        }

        $this->repository->setCurrentEnvironment($environment);
    }

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