<?php

namespace App\Http\Middlewares;

use App\Helpers\JwtHelper;
use App\Http\Controllers\ApiController;
use Closure;
use Exception;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Throwable;

class AuthCheckMiddleware
{
    public function handle(Request $request, Closure $next): mixed
    {
        try {
            $token = $request->bearerToken();
            throw_if(
                trim($token) === '',
                new Exception('JWT is required', Response::HTTP_FORBIDDEN)
            );
            throw_if(
                !(JwtHelper::parseToken($token) && JwtHelper::getSession($token)),
                new Exception('Invalid token', Response::HTTP_FORBIDDEN)
            );
            throw_if(
                !JwtHelper::checkToken($token),
                new Exception('Token is expired', Response::HTTP_UNAUTHORIZED)
            );
            throw_if(
                JwtHelper::getSession($token)->agent->id !== $request->header('API-Key'),
                new Exception('Unauthorized Access', Response::HTTP_FORBIDDEN)
            );
        } catch (Throwable $e) {
            $result = null;
            $meta = null;
            $message = $e->getMessage();
            $errors = null;
            $errorCode = $e->getCode();
            return response()->json(compact('result', 'meta', 'message', 'errors'), in_array($errorCode, ApiController::$statuses) ? $errorCode : Response::HTTP_INTERNAL_SERVER_ERROR);
        }
        return $next($request);
    }

}
