<?php

namespace AutoAdmin\Bundle\Content\Controller;

use AutoAdmin\Bundle\Content\Repository\DefaultTranslatableContentRepository;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class DefaultContentController extends AbstractContentController
{
    public function view(Request $request, EntityManagerInterface $manager): Response
    {
        $route = $request->get('_route');
        $contentClass = $this->config->getContentClassForRoute($route);
        if ($contentClass === null) {
            throw new Exception(sprintf('Could not match content for route "%s"', $route));
        }

        /** @var DefaultTranslatableContentRepository $repository */
        $repository = $manager->getRepository($contentClass);
        $result = $repository->findOneByTranslatedSlug($request->get('slug'), $request->getLocale());

        if ($result === null) {
            throw new NotFoundHttpException();
        }

        return $this->render($this->config->getTemplate($contentClass, 'view'), ['content' => $result,]);
    }
}
