<?php

namespace AutoAdmin\Bundle\Seo\Extractor;

use AutoAdmin\Bundle\Content\Model\PageInterface;
use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Content\Model\TranslationInterface;
use AutoAdmin\Bundle\Seo\Model\SeoContentTranslationInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Contracts\Service\Attribute\Required;

abstract class AbstractExtractor implements ExtractorInterface
{
    protected EntityManagerInterface $entityManager;

    #[Required]
    public function initAbstractExtractor(
        EntityManagerInterface $entityManager
    ): void
    {
        $this->entityManager = $entityManager;
    }

    protected function sanitize(string $input): string
    {
        return strip_tags($input);
    }

    /**
     * @return array<TranslatableInterface,TranslationInterface,SeoContentTranslationInterface>
     */
    protected function getTranslatableTranslationObjects(object $subject): array
    {
        if ($this->isTranslatable($subject)) {
            $translatable = $subject;
            $translation = $subject->getCurrentTranslation();
        } elseif ($this->isTranslation($subject)) {
            $translation = $subject;
            $translatable = $subject->getTranslatable();
        } elseif ($this->isUntranslatedContent($subject)) {
            // untranslated content, self act as translatable and translation
            $translatable = $translation = $subject;
        } else {
            throw new \Exception('Main content should implement some kind of SEO');
        }

        return [$translatable, $translation];
    }

    protected function isTranslatable(object $subject): bool
    {
        return $subject instanceof TranslatableInterface && $subject->getCurrentTranslation() !== null;
    }

    protected function isTranslation(object $subject): bool
    {
        return $subject instanceof TranslationInterface && $subject->getTranslatable() !== null;
    }

    protected function isUntranslatedContent(object $subject): bool
    {
        return $subject instanceof SeoContentTranslationInterface;
    }

    protected function getHomepage(): ?PageInterface
    {
        return $this->entityManager->getRepository(PageInterface::class)
            ->contentFindOneBy(['_.homepage' => true,]);
    }
}
