<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CmsBundle\Page;

use Contao\CoreBundle\Exception\NoRootPageFoundException;
use Contao\CoreBundle\Framework\ContaoFramework;
use Contao\PageModel;
use Ferienpass\CoreBundle\Tenant\TenantRootPage;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
use Symfony\Contracts\Translation\TranslatorInterface;

class PageBuilderFactory
{
    public function __construct(private readonly FragmentHandler $fragmentHandler, private readonly TranslatorInterface $translator, private readonly ContaoFramework $framework, private readonly RequestStack $requestStack, private readonly TenantRootPage $rootPage)
    {
    }

    /**
     * @throws NoRootPageFoundException if no page model is given and the tenant has no published root page to fall back to
     */
    public function create(?PageModel $pageModel = null): PageBuilder
    {
        $this->framework->initialize();

        // Routes that are not Contao pages (login, registration, error screens,
        // …) still need a root page to pull the layout and the page metadata
        // from. Take the tenant's own root page, not merely the first one: on a
        // shared installation "the first root page" is another municipality's
        // site.
        $pageModel ??= $this->rootPage->current();

        if (!$pageModel instanceof PageModel) {
            throw new NoRootPageFoundException('No published root page for the active tenant.');
        }

        return new PageBuilder($pageModel, $this->fragmentHandler, $this->translator, $this->framework, $this->requestStack);
    }
}
