<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;
use Exception;
use Illuminate\Support\Facades\Session;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CustomerJwtMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Check if the custom access-token header is present
        if (!$request->hasHeader('access-token')) {
            return response()->json(['status' => 'error', 'status_code' => 401, 'message' => 'Access token not provided'], 401);
        }

        // Retrieve the token from the custom access-token header
        $token = $request->header('access-token');

        try {
            // Attempt to authenticate the user based on the token
            $user = JWTAuth::setToken($token)->authenticate();

            // Check if authentication was successful and user type is correct
            if (!$user || $user->principal_type_xid !== 3) {
                return response()->json(['status' => 'error', 'status_code' => 401, 'message' => 'Unauthorized access'], 401);
            }

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

        return $next($request);
    }
}
