<?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\SeoContentInterface;
use AutoAdmin\Bundle\Seo\Model\SeoPage;
use Symfony\Component\HttpFoundation\Request;

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

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

    public function extract(Request $request, object $subject, SeoPage $seoPage): SeoPage
    {
        $homepage = $this->getHomepage();
        [$translatable, $translation] = $this->getTranslatableTranslationObjects($subject);

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

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

        return $seoPage;
    }
}
