<?php

namespace app\middleware;

use Shopwwi\WebmanAuth\Auth;
use Shopwwi\WebmanAuth\JWT;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class ExeMiddleware implements MiddlewareInterface
{

    public function process(Request $request, callable $handler): Response
    {
        try {
            $controller = new \ReflectionClass($request->controller);
            $noNeedLogin = $controller->getDefaultProperties()['noNeedLogin']??[];
            if (empty($noNeedLogin) || !in_array($request->action, $noNeedLogin)) {
                $token =  $request->header("Authorization","");
                if (empty($token)) return json(['code'=> 0,'msg'=> trans("error.request")]);
                $uData = explode(" ",$token);
                if (!isset($uData[1])) return json(['code'=> 0,'msg'=> trans("error.request")]);
                $request->uuid = $uData[1];
            }
        } catch (\ReflectionException $exception) {
            return json(['code'=> 500,'msg'=> $exception->getMessage()]);
        }
        $response = $request->method() == 'OPTIONS' ? response('',204) : $handler($request);
        return $response;
    }

}