<?php

namespace app\http\middleware;

use Closure;
use think\{middleware, Request, Response};

class ContextMiddleware extends middleware
{
    public function handle(Request $request, Closure $next): Response
    {
        /*
         * 生成并绑定全局上下文标识ID
         */
        $request->contextId = unique_str();

        /*
         * 数据已加密, 需要先做解密传递处理
         */
        if ($request->header('x-encrypted') == 'true') {
            $encryptedData = $request->param('encryptedData','');
            if($encryptedData) {
                try{
                    $jsonInput = \app\Request::decryptCryptoJSData($encryptedData);
                }catch (\Throwable){
                    $jsonInput = null;
                }

                if(empty($jsonInput)) {
                   return json(['code'=>500,'message'=>'E0.数据解密失败']);
                }
                $request->withInput($jsonInput);
            }
        }

        /**
         * @var Response $response
         */
        $response = $next($request);
        $response->header([
            'R-Context-Id' => $request->contextId,
        ]);

        return $response;
    }
}