<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

/**
 * 权限检查中间件
 * 用法：Route::middleware('permission:crm.lead.create')
 */
class CheckPermission
{
    public function handle(Request $request, Closure $next, string ...$permissions)
    {
        $user = $request->user();

        if (!$user) {
            return response()->json(['code' => 40100, 'message' => '未认证'], 401);
        }

        // 超级管理员直接放行
        if ($user->is_super) {
            return $next($request);
        }

        // 检查权限
        foreach ($permissions as $permission) {
            if (!$user->hasPermission($permission)) {
                return response()->json([
                    'code' => 40300,
                    'message' => '权限不足：' . $permission,
                ], 403);
            }
        }

        return $next($request);
    }
}
