<?php

namespace App\Http\Middleware;

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

class RoleMiddleware
{
    public function handle(Request $request, Closure $next, string $role): Response
    {
        if (!$request->user()) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        $user = $request->user();
        $user->load('role');
        
        $requiredRoles = explode('|', $role);
        $userRole = $user->role ? $user->role->slug : null;
        
        $hasRole = $userRole && in_array($userRole, $requiredRoles);
        
        if (!$hasRole) {
            return response()->json(['error' => 'Forbidden - You do not have the required role'], 403);
        }

        return $next($request);
    }
}
