<?php

declare(strict_types=1);

namespace app\common\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Request;
use Webman\Http\Response;
use app\admin\model\AdminLog as AdminLogModel;

/**
 * 管理员操作日志中间件（Webman 迁移版）
 * 仅对 /admin 路由的 POST、DELETE 请求记录日志
 */
class AdminLog implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        $response = $handler($request);

        $path = trim($request->path(), '/');
        if (str_starts_with($path, 'admin/') && config('buildadmin.auto_write_admin_log', true)) {
            $method = $request->method();
            if ($method === 'POST' || $method === 'DELETE') {
                try {
                    AdminLogModel::instance($request)->record();
                } catch (\Throwable $e) {
                    \support\Log::warning('[AdminLog] ' . $e->getMessage());
                }
            }
        }

        return $response;
    }
}
