<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CmsBundle\Twig\Extension;

use Contao\PageModel;
use Ferienpass\CmsBundle\Translation\DeeplTranslator;
use Symfony\Component\HttpFoundation\RequestStack;
use Twig\Attribute\AsTwigFilter;

class MachineTranslationExtension
{
    public function __construct(
        private readonly DeeplTranslator $translator,
        private readonly RequestStack $requestStack,
    ) {
    }

    #[AsTwigFilter('machine_translate', isSafe: ['html'])]
    public function machineTranslate(?string $content): string
    {
        if ('' === (string) $content) {
            return '';
        }

        $request = $this->requestStack->getCurrentRequest();
        if (null === $request) {
            return $content;
        }

        /** @var PageModel $pageModel */
        $pageModel = $request->attributes->get('pageModel');
        if (!$pageModel instanceof PageModel) {
            return $content;
        }

        $locale = $request->getLocale();
        if ($locale === $pageModel->rootLanguage) {
            return $content;
        }

        return $this->translator->translate($content, $this->translator->getTargetLang($locale), $pageModel->rootLanguage) ?? $content;
    }
}
