<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\PageBuilder\Rendering;

use CpCreation\VitiCore\PageBuilder\Model\Page;
use CpCreation\VitiCore\PageBuilder\Model\Translation\PageTranslation;
use CpCreation\VitiCore\PageBuilder\Repository\PageRepository;

final readonly class PageLayoutManager
{
    public function __construct(
        private PageRepository $pageRepository,
    ) {
    }

    public function ensureGlobalHeaderPage(): Page
    {
        return $this->ensureGlobalLayoutPage(
            PageLayoutResolver::GLOBAL_HEADER_PAGE_CODE,
            'Header global',
            '_layout_header'
        );
    }

    public function ensureGlobalFooterPage(): Page
    {
        return $this->ensureGlobalLayoutPage(
            PageLayoutResolver::GLOBAL_FOOTER_PAGE_CODE,
            'Footer global',
            '_layout_footer'
        );
    }

    public function ensureGlobalLayoutPage(string $code, string $name, string $routeName): Page
    {
        $page = $this->pageRepository->findOneByCode($code);
        if ($page instanceof Page) {
            return $page;
        }

        $page = new Page($code, $name);
        $page->setRouteMode(Page::ROUTE_MODE_SYSTEM);
        $page->setRouteName($routeName);
        $page->setTemplate(Page::TEMPLATE_DEFAULT);
        $page->setSetting('builderMode', 'full');
        $page->setSetting('headerMode', PageLayoutResolver::MODE_NONE);
        $page->setSetting('footerMode', PageLayoutResolver::MODE_NONE);

        $this->hydrateTranslation($page->translate('fr', true), $name);
        $this->hydrateTranslation($page->translate('en', true), $name);

        $this->pageRepository->save($page);

        return $page;
    }

    private function hydrateTranslation(PageTranslation $translation, string $title): void
    {
        $translation->setTitle($title);
        $translation->setPath('');
        $translation->setMetaTitle($title);
    }
}
