<?php

namespace apexl\Io\middleware\permission;

use apexl\Io\modules\user\entities\userEntity;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Routing\RouteContext;

class permissionController implements MiddlewareInterface
{
    public function process(Request $request, RequestHandler $handler): Response
    {
        //always allow OPTIONS
        $method = $request->getMethod();
        if ($method == 'OPTIONS') {
            return $handler->handle($request);
        }

        $uid = $request->getAttribute('user'); // set in an earlier middleware
        $user = new userEntity();
        $user->load($uid);
        // retrieve the configured permission value
        $routeContext = RouteContext::fromRequest($request);
        $route = $routeContext->getRoute();
        $permission = $route->getArgument('permission', 'AllowAll');

        //check if the user accessing this route has permission to do so.
        if (!$user->isAllowed($permission)) {
            return new \Slim\Psr7\Response(403);
        }

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