<?php

declare(strict_types=1);

namespace App\Middleware;

use Psr\Http\Message\ResponseFactoryInterface;
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;

/**
 * Restringe el acceso a una ruta según el rol del usuario autenticado.
 * Debe registrarse después de JwtAuthMiddleware.
 */
class RoleMiddleware implements MiddlewareInterface
{
    private array $rolesPermitidos;
    private ResponseFactoryInterface $responseFactory;

    public function __construct(array $rolesPermitidos, ResponseFactoryInterface $responseFactory)
    {
        $this->rolesPermitidos = $rolesPermitidos;
        $this->responseFactory = $responseFactory;
    }

    public function process(Request $request, RequestHandler $handler): Response
    {
        $rol = $request->getAttribute('usuario_rol');

        if (!in_array($rol, $this->rolesPermitidos, true)) {
            $response = $this->responseFactory->createResponse(403);
            $response->getBody()->write(json_encode(['error' => 'No tiene permisos para esta acción']));

            return $response->withHeader('Content-Type', 'application/json');
        }

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