<?php

declare (strict_types=1);

namespace app\api\middleware;

use think\exception\HttpException;

class CheckParams
{
    public function handle($request, \Closure $next): object
    {

        $params = $request->param();
        if(!isset($params['sign'])){
            return json(['code'=>401,'message'=>'API驗證失敗','data'=>'No Sign','time'=>time()]);
        }      

        $sign = $params['sign'];

        unset($params['sign']);
        unset($params['controller']);
        unset($params['action']);
        unset($params['version']);
        ksort($params);

        $string = md5(md5(strtolower(http_build_query($params))).'seckey');
// print_r($string === $sign);
// var_dump($sign);
// var_dump($string);

        if($string !== $sign){
            // throw new HttpException(401, 'Sign Error!!!');
            return json(['code'=>401,'message'=>'API驗證失敗','data'=>'Sign Error','time'=>time()]);
        }

        $response = $next($request);

        return $response;
    }
}