<?php

namespace App\Http\Middleware;

use App\Services\JwtService;
use Closure;
use Firebase\JWT\ExpiredException;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Throwable;

class ValidateJwt
{

    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, JwtService $jwtService): Response
    {
        $header = $request->header('Authorization');

        if (! $header || ! str_starts_with($header, 'Bearer ')) {
            return response()->json(['message' => 'Missing bearer token.'], 401);
        }

        $token = substr($header, 7);

        try {
            $decoded = $jwtService->decode($token);
            $request->attributes->set('jwt', $decoded);

            return $next($request);
        } catch (ExpiredException $e) {
            return response()->json(['message' => 'Token expired.'], 401);
        } catch (Throwable $e) {
            return response()->json(['message' => 'Invalid token.'], 401);
        }
    }
}