<?php

declare(strict_types=1);

namespace app\vendor\apexl\io\src\Io\middleware;

use apexl\Io\exceptions\SslException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

final readonly class RequireSsl implements MiddlewareInterface
{
    /**
     * @throws SslException
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if (!$this->isSecure()) {
            throw new SslException(
                <<<MESSAGE
                You must either set app.requireSSL to FALSE in config (And use a browser other than Chrome),
                or run this under SSL. NOTE for SSL is required even when tested for chrome as new versions
                of chrome will block non-SSL cookies on cross Site Requests.
                MESSAGE
            );

        }

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

    private function isSecure(): bool
    {
        return isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';
    }
}