<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckPermission
{
    public function handle(Request $request, Closure $next, string $module, string $level = 'read'): Response
    {
        if (!auth()->check()) {
            return redirect('/login');
        }

        $user = auth()->user();

        if ($user->isSuperAdmin()) {
            return $next($request);
        }

        $requiredLevel = match ($level) {
            'read' => 1,
            'write', 'create', 'edit' => 2,
            'delete' => 2,
            default => 1,
        };

        if (!$user->hasPermission($module, $requiredLevel)) {
            abort(403, 'Permesso insufficiente per questa operazione.');
        }

        return $next($request);
    }
}