<?php

namespace AutoAdmin\Bundle\Content\Routing;

use AutoAdmin\Bundle\Content\Configuration\ConfigManager;
use AutoAdmin\Bundle\Content\Entity\Locale;
use AutoAdmin\Bundle\Content\Model\ContentInterface;
use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Content\Model\UnstranslatedInterface;
use AutoAdmin\Bundle\Content\Routing\Exception\ContentRoutingBadParameterException;
use AutoAdmin\Bundle\Content\Routing\Exception\ContentRoutingFailedException;
use AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use AutoAdmin\Bundle\Content\Translation\EntityTranslator;
use AutoAdmin\Bundle\Content\Translation\LocaleResolver;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Routing\RouterInterface;

abstract class AbstractContentAutoRouter implements ContentAutoRouterInterface
{
    protected ?Request $request = null;

    public function __construct(
        protected ConfigManager $config,
        protected RouterInterface $router,
        protected SiteContextHelper $contextHelper,
        protected EntityTranslator $entityTranslator,
        protected LocaleResolver $localeResolver,
    ) {
    }

    protected function addAutoFilledParameters(string $routeName, array $parameters, ?ContentInterface $content): array
    {
        $routeConfig = $this->config->getRoute($routeName);
        $propertyAccessor = new PropertyAccessor();

        if (isset($parameters['_locale']) && $parameters['_locale'] !== null) {
            $localeTranslation = (new Locale($parameters['_locale']));
        } else {
            $localeTranslation = $this->entityTranslator->getLocale();
        }

        foreach ($routeConfig['autofill_parameters'] ?? [] as $key => $propertyPath) {
            $propertyPath = str_replace('_tr.', 'currentTranslation.', $propertyPath);

            if ($content instanceof TranslatableInterface) {
                $parameters[$key] = $this->entityTranslator->translate($content, $propertyPath, $localeTranslation);
            } elseif ($content instanceof UnstranslatedInterface) {
                $parameters[$key] = $propertyAccessor->getValue($content, $propertyPath);
            } else {
                throw new \RuntimeException(
                    'Cannot generate route for classes without'.
                    ' implementing TranslatableInterface or UntranslatedInterface');
            }

            if ($parameters[$key] === null) {
                throw new ContentRoutingBadParameterException($key);
            }
        }

        return $parameters;
    }
}
