<?php

namespace app\middleware;

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

class AuthMiddleware 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('api-type','');
                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")]);
                (new JWT)->guard("admin")->verify();
                $user = (new Auth)->guard("admin")->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()]);
        }
        $response = $request->method() == 'OPTIONS' ? response('',204) : $handler($request);
        // 给响应添加跨域相关的http头
//        $response->withHeaders([
//            'Access-Control-Allow-Credentials' => 'true',
//            'Access-Control-Allow-Origin' => $request->header('origin', '*'),
//            'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
//            'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'),
//        ]);
        return $response;
    }


}