<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Site;

use CpCreation\VitiCore\PageBuilder\Document\BuilderDocumentRenderer;
use CpCreation\VitiCore\PageBuilder\Model\Page;
use CpCreation\VitiCore\PageBuilder\Model\Translation\PageTranslation;
use CpCreation\VitiCore\PageBuilder\Rendering\PageLayoutManager;
use CpCreation\VitiCore\PageBuilder\Repository\PageSectionRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class CmsPageBuilderController extends AbstractController
{
    public function __construct(
        private readonly PageSectionRepository $pageSectionRepository,
        private readonly PageLayoutManager $pageLayoutManager,
        private readonly BuilderDocumentRenderer $builderDocumentRenderer,
    ) {
    }

    #[Route(path: [
        'fr' => '/builder/{id}',
        'en' => '/en/builder/{id}',
    ], name: 'cms_page_builder', priority: 1000)]
    public function show(Page $page, Request $request): Response
    {
        return $this->render('page/builder.html.twig', [
            'page' => $page,
            'pageSections' => $this->pageSectionRepository->findByPageCodeAdmin($page->getCode()),
            'pageDocumentHtml' => $this->builderDocumentRenderer->renderForLocale($page, $request->getLocale()),
            'pageBuilderMode' => true,
            'pageExitUrl' => $this->resolveExitUrl($page, $request->getLocale()),
            'pageLayoutHeaderBuilderUrl' => $this->generateUrl('cms_page_builder', [
                'id' => (string) $this->pageLayoutManager->ensureGlobalHeaderPage()->getId(),
                '_locale' => $request->getLocale(),
            ]),
            'pageLayoutFooterBuilderUrl' => $this->generateUrl('cms_page_builder', [
                'id' => (string) $this->pageLayoutManager->ensureGlobalFooterPage()->getId(),
                '_locale' => $request->getLocale(),
            ]),
        ]);
    }

    private function resolveExitUrl(Page $page, string $locale): string
    {
        if (Page::ROUTE_MODE_SYSTEM === $page->getRouteMode()) {
            $path = trim((string) $page->getSetting('sourcePath', ''));

            return '' !== $path ? $path : $this->generateUrl('cms_homepage', ['_locale' => $locale]);
        }

        $translation = $this->findTranslation($page, $locale);
        if (!$translation instanceof PageTranslation) {
            return $this->generateUrl('cms_homepage', ['_locale' => $locale]);
        }

        if ('' === $translation->getPath()) {
            return $this->generateUrl('cms_homepage', ['_locale' => $translation->getLocale()]);
        }

        return $this->generateUrl('cms_page', [
            '_locale' => $translation->getLocale(),
            'path' => $translation->getPath(),
        ]);
    }

    private function findTranslation(Page $page, string $locale): ?PageTranslation
    {
        foreach ($page->getTranslations() as $translation) {
            if ($translation instanceof PageTranslation && $translation->getLocale() === $locale) {
                return $translation;
            }
        }

        foreach ($page->getTranslations() as $translation) {
            if ($translation instanceof PageTranslation) {
                return $translation;
            }
        }

        return null;
    }
}
