<?php

declare(strict_types=1);

namespace Gls\GlsPoland\MessageHandler\Configuration;

use Gls\GlsPoland\Configuration\Api;
use Gls\GlsPoland\Message\UpdateApiConfigurationCommand;
use Psr\Cache\CacheItemPoolInterface;

final class UpdateApiConfigurationHandler implements UpdateApiConfigurationHandlerInterface
{
    private $configuration;
    private $cache;

    public function __construct(Api\PersistentConfigurationInterface $configuration, CacheItemPoolInterface $cache)
    {
        $this->configuration = $configuration;
        $this->cache = $cache;
    }

    public function handle(UpdateApiConfigurationCommand $command): void
    {
        $sandboxEnabled = $this->configuration->isSandboxEnabled();

        $this->configuration->save($command->getConfiguration());

        if ($sandboxEnabled !== $this->configuration->isSandboxEnabled()) {
            $this->cache->clear();
        }
    }
}
