<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class CheckTeamLevel
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, int $requiredLevel = 3): Response
    {
        $user = Auth::user();

        // Check if user is authenticated
        if (!$user) {
            return redirect()->route('home')->with('error', 'Authentication required.');
        }

        // Check if user has required role level
        if (!method_exists($user, 'hasRoleLevel') || !$user->hasRoleLevel($requiredLevel)) {
            return redirect()->route('home')->with('error', 'Access denied. Insufficient privileges (Level ' . $requiredLevel . '+ required).');
        }

        return $next($request);
    }
}
