<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\middleware;

use app\model\AdminUser;
use app\service\AdminOperationLogService;


/**
 * 管理员操作日志中间件
 * 记录管理员的每次请求操作
 * @package app\middleware
 */
class AdminOperationLog
{
    /**
     * 处理请求并记录操作日志
     * @param mixed $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        $response = $next($request);

        try {
            $path = (string)$request->pathinfo();
        } catch (\Throwable $e) {
            $path = '';
        }

        if (strpos($path, 'api/admin/auth/login') !== false) {
            return $response;
        }

        $uid = $request->uid ?? null;
        if (!$uid) {
            return $response;
        }

        $user = null;
        try {
            $user = AdminUser::find($uid);
        } catch (\Throwable $e) {
            $user = null;
        }

        if (!$user || (int)($user->status ?? 0) !== 1) {
            return $response;
        }

        $statusCode = 200;
        if (is_object($response) && method_exists($response, 'getCode')) {
            try {
                $statusCode = (int)$response->getCode();
            } catch (\Throwable $e) {
                $statusCode = 200;
            }
        }

        AdminOperationLogService::record(
            AdminOperationLogService::buildPayload($request, (string)$user->username, $statusCode)
        );

        return $response;
    }
}
