<?php

namespace app\middleware;

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

class WxMiddleware 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)) {
                $type = $request->header('platform','');
                if (empty($type)) return json(['code'=> 0,'msg'=> trans("error.param")]);
                $token =  $request->header("Authorization","");
                if (empty($token)) return json(['code'=> 0,'msg'=> trans("error.request")]);
                if ($type == "mini") {
                    $typeName = "member";
                } else {
                    $typeName = "mp";
                }
                (new JWT)->guard($typeName)->verify();
                $user = (new Auth)->guard($typeName)->user();
                if (empty($user)) return json(['code'=>401,'msg'=> trans("error.login")]);
                $request->user = $user->toArray();
            }
        } catch (\ReflectionException $exception) {
            return json(['code'=> 500,'msg'=> $exception->getMessage()]);
        }
        return $request->method() == 'OPTIONS' ? response('',204) : $handler($request);
    }

}