<?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\Message;

use InPost\International\Configuration\EnvironmentConfiguration;
use InPost\International\Configuration\Repository\ApiConfigurationRepositoryInterface;
use InPost\International\Environment\EnvironmentInterface;
use Symfony\Component\Validator\Constraints as Assert;

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

final class UpdateApiConfigurationCommand
{
    /**
     * @var EnvironmentInterface|null
     *
     * @Assert\NotNull
     */
    private $environment;

    /**
     * @var array<string, EnvironmentConfiguration> configurations by env ID
     *
     * @Assert\Valid
     */
    private $configurations = [];

    public static function forRepository(ApiConfigurationRepositoryInterface $repository): self
    {
        $command = new self();

        $command->setEnvironment($repository->getCurrentEnvironment());
        foreach ($repository->getAllConfigurations() as $configuration) {
            $command->addConfiguration($configuration);
        }

        return $command;
    }

    public function getEnvironment(): ?EnvironmentInterface
    {
        return $this->environment;
    }

    public function setEnvironment(?EnvironmentInterface $environment): void
    {
        $this->environment = $environment;
    }

    public function getConfigurations(): array
    {
        return $this->configurations;
    }

    public function getConfiguration(string $env): ?EnvironmentConfiguration
    {
        return $this->configurations[$env] ?? null;
    }

    public function addConfiguration(EnvironmentConfiguration $configuration): void
    {
        $env = $configuration->getEnvironment()->getId();
        $this->configurations[$env] = $configuration;
    }

    public function removeConfiguration(EnvironmentConfiguration $configuration): void
    {
        if (false !== $key = array_search($configuration, $this->configurations, true)) {
            unset($this->configurations[$key]);
        }
    }
}
