<?php

namespace AutoAdmin\Bundle\Content\Duplicator;

use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Content\Translation\EntityTranslator;
use Symfony\Contracts\Service\Attribute\Required;

class TranslatableDuplicator extends AbstractDuplicator
{
    protected EntityTranslator $entityTranslator;

    #[Required]
    public function inject(EntityTranslator $entityTranslator): void
    {
        $this->entityTranslator = $entityTranslator;
    }

    /**
     * @return string[]
     */
    public function supportInterfaces(): array
    {
        return [
            TranslatableInterface::class,
        ];
    }

    /**
     * @param TranslatableInterface $entity
     * @param TranslatableInterface $duplicate
     *
     * @return TranslatableInterface
     */
    public function duplicate(object $entity, object $duplicate): object
    {
        $translations = $entity->getTranslations();

        // Reset empty translation
        $duplicate->getTranslations()->clear();

        foreach ($translations as $translation) {
            $duplicateTranslation = $this->duplicatorManager->duplicate($translation);
            $duplicate->addTranslation($duplicateTranslation);
        }

        $this->entityTranslator->initializeCurrentTranslationFromContext($duplicate);

        return $duplicate;
    }
}
