<?php
namespace app\adminVue\controller;

use think\exception\HttpResponseException;
use think\facade\Log;

class V2ApiMiddleware
{
    public function handle($request, \Closure $next)
    {
        try {
            // Bound all paginated requests, including business code using the existing ORM extension.
            foreach (['page'=>1000000, 'limit'=>100] as $key=>$max) {
                $value = $request->get($key, $key === 'page' ? 1 : 15);
                if (!is_scalar($value) || !preg_match('/^[1-9][0-9]*$/D', (string)$value) || (float)$value > $max) {
                    return json(['code'=>422,'msg'=>'分页参数无效','data'=>null], 422);
                }
            }
            $response = $next($request);
        } catch (HttpResponseException $e) {
            $response = $e->getResponse();
        } catch (\Throwable $e) {
            $id = bin2hex(random_bytes(8));
            Log::error('admin-v2 '.$id.' '.$e);
            $response = json(['code'=>500,'msg'=>'操作失败，请重试或联系管理员','data'=>null,'requestId'=>$id], 500);
        }
        if($request->method()==='POST' && $response->getCode()<400)try { \app\mobile\service\MessageInbox::invalidate(); } catch(\Throwable $error) { Log::warning('admin inbox cache invalidation unavailable'); }
        return $response->header(['Cache-Control'=>'no-store', 'X-Content-Type-Options'=>'nosniff']);
    }
}
