<?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\AdminBundle\Controller\Fragment;

use Contao\CoreBundle\EventListener\SubrequestCacheSubscriber;
use Ferienpass\AdminBundle\Tenant\TenantSwitcher;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;

/**
 * The persistent reminder that a global admin has stepped into another
 * municipality's data room: every admin page carries the banner (and a frame
 * around the viewport) until they leave, because every view, change and mail
 * in between affects that municipality — not their own.
 *
 * Rendered as an ESI fragment like the impersonation banner: the decision
 * depends on the session, so it must never end up in a shared cache.
 */
final class TenantSwitchBannerController extends AbstractController
{
    public function __construct(private readonly TenantSwitcher $tenantSwitcher)
    {
    }

    public function __invoke(): Response
    {
        $tenant = $this->tenantSwitcher->isAvailable() ? $this->tenantSwitcher->selected() : null;

        $response = null !== $tenant
            ? $this->render('@FerienpassAdmin/fragment/tenant_switch_banner.html.twig', [
                'tenant' => $tenant,
            ])
            : new Response('');

        $response->setPrivate();
        $response->headers->addCacheControlDirective('no-store');
        $response->headers->addCacheControlDirective('must-revalidate');
        $response->setVary(['Cookie']);
        $response->headers->set(SubrequestCacheSubscriber::MERGE_CACHE_HEADER, '1');

        return $response;
    }
}
