<?php
declare(strict_types=1);

namespace Celena\Core\Template;

use Celena\Core\Container;

/**
 * Реестр async-блоков для тега {async block="name"}.
 * Каждый блок — callable (Container $c, array $params): array{template:string, vars:array}
 * Шаблон рендерится Engine'ом и отдаётся клиенту через /api/blocks/{name}.
 */
final class BlockRegistry
{
    /** @var array<string, callable> */
    private array $blocks = [];

    public function register(string $name, callable $resolver): void
    {
        $this->blocks[$name] = $resolver;
    }

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

    /** @return array{template:string, vars:array<string,mixed>}|null */
    public function resolve(string $name, Container $container, array $params): ?array
    {
        if (!isset($this->blocks[$name])) {
            return null;
        }
        $result = ($this->blocks[$name])($container, $params);
        if (!is_array($result) || !isset($result['template'])) {
            return null;
        }
        return [
            'template' => (string) $result['template'],
            'vars' => (array) ($result['vars'] ?? []),
        ];
    }

    /** @return string[] */
    public function names(): array { return array_keys($this->blocks); }
}
