<?php

declare(strict_types=1);

namespace App\Http;

use App\Auth\SessionManager;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Views\Twig;

/**
 * Pushes per-request data into Twig globals so templates can render
 * without each controller building a context array:
 *
 *   - `csrf_token` — the current session's CSRF token (set by CsrfMiddleware).
 *   - `csp_nonce` — per-request nonce (set by CspMiddleware) so templates
 *     can stamp `nonce="…"` on inline `<script>` blocks.
 *   - `flash` — flash messages drained from the session.
 *   - `current_user` — the logged-in `UserContext` or null.
 *   - `oidc_enabled`, `local_admin_enabled` — login form toggles.
 *   - `app_env` — for dev-only banners / cache headers.
 *
 * Runs after Session + Csrf so the values are in place by the time the
 * controller renders.
 */
final class TwigGlobalsMiddleware implements MiddlewareInterface
{
    /**
     * @param array<string, mixed> $configFlags
     */
    public function __construct(
        private readonly Twig $twig,
        private readonly SessionManager $sessions,
        private readonly array $configFlags,
    ) {
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $env = $this->twig->getEnvironment();
        $env->addGlobal('csrf_token', $request->getAttribute(CsrfMiddleware::ATTR_TOKEN));
        $env->addGlobal('csp_nonce', $request->getAttribute(CspMiddleware::ATTR_NONCE, ''));
        $env->addGlobal('flash', $this->sessions->consumeFlash());
        $env->addGlobal('current_user', $this->sessions->getUser());
        foreach ($this->configFlags as $key => $value) {
            $env->addGlobal($key, $value);
        }

        return $handler->handle($request);
    }
}
