<?php 
declare(strict_types=1); 
namespace App;
  // AuthMiddleware.php

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Firebase\JWT\JWT;
use Slim\App;

class AuthMiddleware
{
//     public function __invoke(Request $request, Response $response, Route $next): ResponseInterface
    public function __invoke(Request $request, Response $response, Route $next)
    {
        $token = $this->getTokenFromHeader($request);

        if (!$token) {
            return $response->withStatus(401)->withJson(['error' => 'Unauthorized']);
        }

        try {
            // Verificar y decodificar el token JWT`
            $decoded = JWT::decode($token, getenv('SECRET_KEY'), ['HS256']);
            // Agregar los datos decodificados a la solicitud para su uso posterior en las rutas
            $request = $request->withAttribute('token', $decoded);
            // Continuar con la ejecución de las rutas
            return $next($request, $response);
        } catch (\Exception $e) {
            return $response->withStatus(401)->withJson(['error' => 'Unauthorized']);
        }
    }

    private function getTokenFromHeader(Request $request): ?string
    {
        $header = $request->getHeaderLine('Authorization');
        if (strpos($header, 'Bearer ') === 0) {
            return substr($header, 7);
        }
        return null;
    }
}
