<?php

declare(strict_types=1);

final class MyronCallableSectionRenderer implements MyronSectionRenderer
{
    private Closure $matcher;
    private Closure $renderer;

    public function __construct(
        private readonly string $rendererId,
        callable $matcher,
        callable $renderer,
        private readonly int $rendererPriority = 0,
        private readonly ?MyronSectionContract $sectionContract = null,
    ) {
        $id = trim($rendererId);
        if ($id === '') {
            throw new InvalidArgumentException('Section renderer id is required.');
        }
        $this->matcher = Closure::fromCallable($matcher);
        $this->renderer = Closure::fromCallable($renderer);
    }

    public function id(): string
    {
        return $this->rendererId;
    }

    public function priority(): int
    {
        return $this->rendererPriority;
    }

    public function canRender(MyronSectionRenderContext $context): bool
    {
        return (bool) ($this->matcher)($context);
    }

    public function render(MyronSectionRenderContext $context): string
    {
        return (string) ($this->renderer)($context);
    }

    public function contract(): ?MyronSectionContract
    {
        return $this->sectionContract;
    }
}
