<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Auth;

use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Support\Facades\Session;

class CheckUserStatus
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */


    public function handle(Request $request, Closure $next): Response
    {
        if (!$request->hasHeader('Authorization')) {
            return response()->json([
                'status' => 'error',
                'status_code' => 401,
                'message' => 'Access token not provided'
            ], 401);
        }

        $token = $request->header('Authorization');
        $token = str_replace('Bearer ', '', $token);

        try {
            $payload = JWTAuth::setToken($token)->getPayload();

            Session::flash('vendorToken', $token);
        } catch (JWTException $e) {
            return response()->json([
                'status' => 'error',
                'status_code' => 401,
                'message' => 'Invalid token'
            ], 401);
        }

        return $next($request);
    }
}
