<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Exceptions\JWTException;

class JwtMiddleware
{
    public function handle($request, Closure $next)
    {
        try {
            // Check for token validity
            $user = JWTAuth::parseToken()->authenticate();
            $request->attributes->add(['user_id' => $user->id]);
        } catch (TokenExpiredException $e) {
            // Token has expired
            return response()->json(['error' => 'Token has expired'], 401);
        } catch (TokenInvalidException $e) {
            // Invalid token
            return response()->json(['error' => 'Invalid token'], 401);
        } catch (JWTException $e) {
            // Token not provided
            return response()->json(['error' => 'Token not provided'], 401);
        }

        return $next($request);
    }
}
