<?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;

/**
 * Boots the PHP session and exposes the `SessionManager` for the rest of
 * the chain via the `session` request attribute. Refreshes the activity
 * timestamp on every request that already has a logged-in user so the
 * 8 h idle timeout works.
 */
final class SessionMiddleware implements MiddlewareInterface
{
    public const ATTR_SESSION = 'session';

    public function __construct(private readonly SessionManager $sessions)
    {
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $this->sessions->startSession();
        $this->sessions->refreshActivity();

        return $handler->handle($request->withAttribute(self::ATTR_SESSION, $this->sessions));
    }
}
