<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\PageBuilder\Builder;

final class BuilderSchemaRegistry
{
    /**
     * @param iterable<BuilderSchemaProviderInterface> $providers
     */
    public function __construct(private readonly iterable $providers)
    {
    }

    /**
     * @return array<string, mixed>|null
     */
    public function pageConfig(string $pageCode): ?array
    {
        foreach ($this->providers as $provider) {
            $config = $provider->pageConfig($pageCode);
            if (\is_array($config)) {
                return $config;
            }
        }

        return null;
    }

    /**
     * @return array<string, mixed>|null
     */
    public function schemaForComponent(string $component): ?array
    {
        foreach ($this->providers as $provider) {
            $schema = $provider->schemaForComponent($component);
            if (\is_array($schema)) {
                $schema['component'] ??= $component;

                return $schema;
            }
        }

        return null;
    }

    /**
     * @param iterable<string> $components
     *
     * @return array<string, array<string, mixed>>
     */
    public function schemasForComponents(iterable $components): array
    {
        $schemas = [];
        foreach ($components as $component) {
            $component = trim($component);
            if ('' === $component || isset($schemas[$component])) {
                continue;
            }

            $schema = $this->schemaForComponent($component);
            if (\is_array($schema)) {
                $schemas[$component] = $schema;
            }
        }

        ksort($schemas, \SORT_STRING);

        return $schemas;
    }
}
