<?php
declare(strict_types=1);

namespace ProudNerds\Block;

use Timber\Post;
use Timber\Timber;

final class BlockRenderer
{
    public function __invoke(string $content, array $block): string
    {
        if ($block['blockName'] === null || $content === '') {
            return $content;
        }

        if ($this->isOwnBlock($block['blockName'])) {
            \remove_filter('the_content', 'wpautop');
            return $content;
        }

        global $post;

        $templateFile = 'views/blocks/wp-block.twig';

        $context = [
            'content' => $content,
            'block' => $block,
            'post' => new Post($post)
        ];
        return Timber::fetch($templateFile, $context) ?: $content;
    }

    private function isOwnBlock(string $blockName): bool
    {
        return \str_starts_with($blockName, Block::NAME_PREFIX);
    }
}
