<?php

namespace App\Http\Middleware;

use App\Traits\JsonResponseTrait;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;
use PHPOpenSourceSaver\JWTAuth\Exceptions\TokenExpiredException;
use PHPOpenSourceSaver\JWTAuth\Exceptions\JWTException;

class UserMiddleware
{
    use JsonResponseTrait;
    public function handle(Request $request, Closure $next)
    {
        try {
            $user = auth('user')->user(); // // Get the currently authenticated user
            if (!$user) {
                return $this->errorResponse(statusCode: 403, message: 'Unauthorized user access');
            }
            $request->merge(['auth_user' => $user]);
        } catch (TokenExpiredException $e) {
            return $this->errorResponse(statusCode: 401, message: 'Token has expired');
        } catch (JWTException $e) {
            return $this->errorResponse(statusCode: 400, message: 'Token is missing or malformed');
        } catch (\Exception $e) {
            echo "Error: ". $e;
            return $this->errorResponse(statusCode: 401, message: 'Authentication failed');
        }

        return $next($request);
    }
}