<?php


namespace AutoAdmin\Bundle\Seo\EventListener;


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

class ContentMetadataEventListener
{
    private ExtractorManager $extractorManager;

    public function __construct(ExtractorManager $extractorManager)
    {
        $this->extractorManager = $extractorManager;
    }

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

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

            $request = $event->getRequest();

            if ($seo = $this->extractorManager->extract($request, $content, $contentContext->getSeoPage())) {
                $contentContext->setSeoPage($seo);
            }
        }
    }
}
