<?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;
use Illuminate\Support\Facades\Log;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class VendorMiddleware
{
    use JsonResponseTrait;

    public function handle(Request $request, Closure $next): Response
    {
        try {
            $accessToken = $request->bearerToken();
            Log::info('Access token: ' . $accessToken);
            JWTAuth::setToken($accessToken);
            $payload = JWTAuth::getPayload();
            $userId = $payload->get('sub'); // Standard JWT claim for user ID
            $user = User::find($userId);

            if (!$user || !$user->isVendor()) {
                return $this->errorResponse(statusCode: 403, message: 'Unauthorized vendor access');
            }

            // Set authenticated user
            Auth::setUser($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');
            Log::error('JWT exception: ' . $e->getMessage());
        } catch (\Exception $e) {
            return $this->errorResponse(statusCode: 401, message: 'Authentication failed');
        }

        return $next($request);
    }
}
