<?php

namespace Kylin\Rbac\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Kylin\Core\ApiResponse;
use Symfony\Component\HttpFoundation\Response;

/**
 * 权限验证中间件
 *
 * 验证当前用户是否拥有指定权限，无权限返回 403。
 */
class VerifyPermission
{
    public function handle(Request $request, Closure $next, string ...$permissions): Response
    {
        if (! $request->user()) {
            return ApiResponse::error('CORE-AUTH-001', '未认证', 401);
        }

        foreach ($permissions as $permission) {
            if (! $request->user()->hasPermissionTo($permission)) {
                return ApiResponse::error('CORE-PERM-001', '无权执行此操作', 403);
            }
        }

        return $next($request);
    }
}
