<?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\CoreBundle\Twig;

use Ferienpass\CoreBundle\Tenant\Surface;
use Ferienpass\CoreBundle\Tenant\SurfaceContext;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

/**
 * Lets a template ask whether there is a public site to link to.
 *
 * A municipality can run the admin without a CMS, and then every "look at it
 * on the site" affordance is pointing at something that does not exist — the
 * URL generator cannot invent a host for it, so the template has to leave the
 * link out.
 */
class SurfaceExtension extends AbstractExtension
{
    public function __construct(private readonly SurfaceContext $surfaces)
    {
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('has_public_site', $this->hasPublicSite(...)),
            new TwigFunction('public_site_is_here', $this->publicSiteIsHere(...)),
        ];
    }

    public function hasPublicSite(): bool
    {
        return $this->publicSiteIsHere() || null !== $this->surfaces->hostFor(Surface::Frontend);
    }

    /**
     * Whether the public site shares this domain — and therefore this session.
     * Anything that seeds the frontend session from the admin (impersonation)
     * only works while it does.
     */
    public function publicSiteIsHere(): bool
    {
        return !$this->surfaces->isEnabled() || $this->surfaces->serves(Surface::Frontend);
    }
}
