<?php


namespace AutoAdmin\Bundle\Seo\EventListener;


use AutoAdmin\Bundle\Content\Context\ContentContext;
use Symfony\Component\HttpKernel\Event\ResponseEvent;

class SchemaRenderEventListener
{
    private ContentContext $contentContext;

    public function __construct(ContentContext $contentContext)
    {
        $this->contentContext = $contentContext;
    }

    public function onKernelResponse(ResponseEvent $event): void
    {
        $request = $event->getRequest();
        $route = $request->get('_route');
        $response = $event->getResponse();

        if (
            $route === null
            || substr($route, 0, 1) === '_'
        ) {
            return;
        }

        $schema = $this->contentContext->getSchema();
        $contentType = $response->headers->get('content-type');
        if (
            $schema
            && $schema->hasRepresentations()
            && stripos($contentType, 'text/html') === 0
        ) {
            $content = str_replace('</body>', $schema->toScript() . '</body>', $response->getContent());
            $response->setContent($content);
        }
    }
}
