<?php
namespace Opentalent\OtConnect\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use TYPO3\CMS\Core\Http\RedirectResponse;

/**
 * Hooks into the frontend request and process the request in order to
 * rewrite the uri and remove the 'logintype=logout' part after it was processed.
 *
 * @internal
 */
class RequestHandler implements MiddlewareInterface
{
    public function __construct() {}

    /**
     *
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $uri = $request->getUri();
        if (preg_match("/^(.*&)*logintype=logout(&.*)*$/", $uri->getQuery())) {
            // this is a logout request, and it has already been handled by the
            // auth service.
            $newQuery = preg_replace("/logintype=logout&?/", '', $uri->getQuery());

            return new RedirectResponse(
                $uri->withQuery($newQuery),
                303,
                ['X-Redirect-By' => 'OtConnect logout redirection']
            );
        }

        // just pass the plate to the next middleware...
        return $handler->handle($request);
    }
}
