<?php


namespace AutoAdmin\Bundle\Seo\Extractor;


use AutoAdmin\Bundle\Content\Configuration\ConfigManager;
use AutoAdmin\Bundle\Content\Routing\ContentRouter;
use AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use AutoAdmin\Bundle\Seo\Model\SchemaOrgContentInterface;
use AutoAdmin\Bundle\Seo\Model\SchemaOrgContentTranslationInterface;
use AutoAdmin\Bundle\Seo\Model\SeoPage;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;

class SchemaOrgExtractor extends AbstractExtractor
{
    public function __construct(
        protected ConfigManager $config,
        protected ContentRouter $contentRouter,
        protected SiteContextHelper $contextHelper,
        protected EntityManagerInterface $em,
    ) {
    }

    public function supports($subject, $route): bool
    {
        return $this->isTranslatable($subject)
            || $this->isTranslation($subject)
            || $this->isUntranslatedContent($subject);
    }

    public function extract(Request $request, $subject, $seo): SeoPage
    {
        $homepage = $this->getHomepage();
        list($translatable, $translation) = $this->getTranslatableTranslationObjects($subject);

        // schema.org
        $isSchemaOverride = false;
        if ($translatable instanceof SchemaOrgContentInterface
            && $translation instanceof SchemaOrgContentTranslationInterface
            && $schemaOrg = $translation->getSchemaOrgMetadata()
        ) {
            $isSchemaOverride = $schemaOrg->getOverride();
            $seo->appendStructuredData($schemaOrg);
        }

        // only keep homepage schema if no override, and if main content is not already homepage
        if (!$isSchemaOverride && $translatable != $homepage) {
            $seo->appendStructuredData($homepage->getCurrentTranslation()->getSchemaOrgMetadata(), true);
        }

        return $seo;
    }
}
