<?php

namespace AutoAdmin\Bundle\Seo\EventListener;

use AutoAdmin\Bundle\Content\Event\ContentMetadataEvent;
use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Seo\Extractor\ExtractorManager;

class ContentMetadataEventListener
{
    public function __construct(
        private readonly ExtractorManager $extractorManager,
    ) {
    }

    public function onContentMetadata(ContentMetadataEvent $event): void
    {
        $contentContext = $event->getContentContext();

        $content = $contentContext->getMainContent();
        $seoPage = $contentContext->getSeoPage();
        if ($content instanceof TranslatableInterface) {
            $content = $content->getCurrentTranslation();
        }

        if ($content === null || $seoPage === null) {
            return;
        }

        if ($extract = $this->extractorManager->extract($event->getRequest(), $content, $seoPage)) {
            $contentContext->setSeoPage($extract);
        }
    }
}
