<?php

namespace AutoAdmin\Bundle\Content\Controller;

use AutoAdmin\Bundle\Content\Entity\Page;
use AutoAdmin\Bundle\Content\Repository\AbstractTranslatableContentRepository;
use Exception;
use ReflectionException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class PageController extends AbstractContentController
{
    private const CONTENT_SLUG = 'page';

    /**
     * @throws ReflectionException
     * @throws Exception
     */
    public function index(Request $request): Response
    {
        $config = $this->config->getContentConfig(self::CONTENT_SLUG);
        if ($config === null) {
            throw new Exception(sprintf('Please define a content for slug "%s"', self::CONTENT_SLUG));
        }

        /** @var AbstractTranslatableContentRepository $repository */
        $repository = $this->em->getRepository($config['class']);
        $homePage = $repository->contentFindOneBy(['_.homepage' => true,]);

        if ($homePage === null || $homePage->getCurrentTranslation() === null) {
            throw new NotFoundHttpException('No homepage found or homepage translation missing.');
        }

        return $this->render(
            $this->getTemplate(self::CONTENT_SLUG, 'index'),
            [
                'content' => $homePage,
            ]
        );
    }

    public function view(Request $request): Response
    {
        $result = $this->contentContext->getMainContent();

        if (
            $result === null
            || $result->getCurrentTranslation() === null
            || (
                $request->get('_route') !== 'page_index'
                && $result instanceof Page
                && $result->isHomepage()
            )
        ) {
            if ($result instanceof Page && $result->isHomepage()) {
                return $this->redirectToRoute('page_index', [], Response::HTTP_MOVED_PERMANENTLY);
            }

            throw new NotFoundHttpException();
        }

        return $this->render($this->getTemplate(self::CONTENT_SLUG), ['content' => $result,]);
    }
}
