<?php
declare (strict_types=1);

namespace app\middleware;

use app\service\PermissionService;

class AuthMiddleware
{
    /**
     * 处理请求
     */
    public function handle($request, \Closure $next)
    {
        // 获取当前控制器和操作
        $controller = $request->controller();
        $action = $request->action();
        
        // 检查是否在登录白名单中（不需要登录验证）
        if (PermissionService::isInLoginWhitelist($controller, $action)) {
            return $next($request);
        }
        
        // 验证登录状态
        $userInfo = $this->checkLogin($request);
        if (!$userInfo) {
            return json_error([], '请先登录', 401);
        }
        
        // 将用户信息注入请求
        $request->userInfo = $userInfo;
        $request->userId = (int)$userInfo['user_id'];
        
        // 检查是否在权限白名单中（需要登录但不需要权限验证）
        if (PermissionService::isInPermissionWhitelist($controller, $action)) {
            return $next($request);
        }
        
        // 验证权限
        if (!PermissionService::checkPermission((int)$userInfo['user_id'], $controller, $action)) {
            return json_error([], '无权限访问', 403);
        }
        
        return $next($request);
    }
    
    /**
     * 检查登录状态
     */
    protected function checkLogin($request): ?array
    {
        $token = $request->cookie('auth_token');
        if (!$token) {
            return null;
        }
        
        $decoded = parseToken($token);
        if (!$decoded) {
            return null;
        }
        
        return $decoded;
    }
}