<?php

namespace App\Http\Middleware;

use App\Core\Request;
use App\Core\Response;
use App\Domain\Repositories\TokenRepositoryInterface;
use App\Exceptions\AuthException;

class VerifyJWTBlacklist
{
    public function __construct(private TokenRepositoryInterface $tokens)
    {
    }

    public function handle(Request $request, callable $next): Response
    {
        $decoded = $request->attribute('jwt');
        $jti = $decoded->jti ?? null;

        if (!$jti) {
            throw new AuthException('Invalid token structure: missing jti claim', 401);
        }

        if ($this->tokens->isJtiBlacklisted($jti)) {
            throw new AuthException('Token has been revoked', 401);
        }

        return $next($request);
    }
}
