<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\PageBuilder\Block;

use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;

final class BlockTypeRegistry
{
    /**
     * @var array<string, BlockTypeInterface>
     */
    private array $blockTypes = [];

    /**
     * @param iterable<BlockTypeInterface> $blockTypes
     */
    public function __construct(
        #[AutowireIterator('viti-core.page_builder.block_type')]
        iterable $blockTypes,
    ) {
        foreach ($blockTypes as $blockType) {
            $this->blockTypes[$blockType->getCode()] = $blockType;
        }
    }

    /**
     * @return list<BlockTypeInterface>
     */
    public function all(): array
    {
        return array_values($this->blockTypes);
    }

    public function has(string $code): bool
    {
        return isset($this->blockTypes[$code]);
    }

    public function find(string $code): ?BlockTypeInterface
    {
        return $this->blockTypes[$code] ?? null;
    }

    public function get(string $code): BlockTypeInterface
    {
        $blockType = $this->find($code);

        if ($blockType instanceof BlockTypeInterface) {
            return $blockType;
        }

        throw new \InvalidArgumentException(sprintf('Le type de bloc "%s" est inconnu.', $code));
    }
}
