<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\DocStoreBundle\GenericDoc\Twig;

use Chill\DocStoreBundle\GenericDoc\GenericDocDTO;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Twig\Extension\RuntimeExtensionInterface;

final readonly class GenericDocExtensionRuntime implements RuntimeExtensionInterface
{
    public function __construct(
        /**
         * @var list<GenericDocRendererInterface>
         */
        private iterable $renderers,
    ) {}

    /**
     * @throws RuntimeError
     * @throws SyntaxError
     * @throws LoaderError
     */
    public function renderGenericDoc(Environment $twig, GenericDocDTO $genericDocDTO, array $options = []): string
    {
        foreach ($this->renderers as $renderer) {
            if ($renderer->supports($genericDocDTO)) {
                return $twig->render(
                    $renderer->getTemplate($genericDocDTO, $options),
                    $renderer->getTemplateData($genericDocDTO, $options),
                );
            }
        }

        throw new \LogicException('no renderer found');
    }
}
