<?php
namespace app\adminapi\middleware;

use ReflectionClass;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class AdminJwtCheck implements MiddlewareInterface
{
    public function process(Request $request, callable $handler) : Response
    {   
        // 檢查是否在白名單
        if($request->controller == 'app\adminapi\controller\AuthController'){
            return $handler($request);
        }

        $token = $request->header('Authorization');
        
        if(!$token){
            return json([
                'code' => 401,
                'message' => '請登入後再操作'
            ]);
        }

        $token = str_replace('Bearer ', '', $token);

        $key = 'jwtkey123456';

        try{

            $decoded = JWT::decode($token, new Key($key, 'HS256'));

            $request->uid = $decoded->uid;

            $response = $handler($request);

            return $response;
    
        }catch(\Exception $e){

            return json([
                'code' => 401,
                'message' => '操作失敗，請重新登入',
                'data' => $e->getMessage()
            ]);
        }
    }
}