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

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

final class EnvironmentRegistry
{
    /**
     * @var array<string, EnvironmentInterface>
     */
    private $environments = [];

    /**
     * @param iterable<EnvironmentInterface> $environments
     */
    public function __construct(iterable $environments = [])
    {
        foreach ($environments as $environment) {
            $this->register($environment);
        }
    }

    public function register(EnvironmentInterface $environment): void
    {
        if ($this->has($id = $environment->getId())) {
            throw new \LogicException(sprintf('Environment "%s" is already registered.', $id));
        }

        $this->environments[$id] = $environment;
    }

    /**
     * @return EnvironmentInterface[]
     */
    public function getAll(): array
    {
        return $this->environments;
    }

    public function has(string $id): bool
    {
        return array_key_exists($id, $this->environments);
    }

    public function get(string $id): EnvironmentInterface
    {
        if (!$this->has($id)) {
            throw new \LogicException(sprintf('Unknown environment: "%s".', $id));
        }

        return $this->environments[$id];
    }
}
