<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;
use App\Exceptions\NotAuthorizedException;

class RoleMiddleware {
    public function handle($request, Closure $next, $raw_roles) {
        $user = $request->user;
        $roles = explode('|', $raw_roles);
        $has_permission = false;

        foreach($roles as $role){
            $has_permission = $has_permission || $user->hasRole($role);
        }

        if(!$has_permission) {
            Log::warning('El usuario intento acceder a una ruta sin los roles necesarios', [
                'user' => $user->id,
                'required_roles' => $raw_roles,
                'user_roles' => implode('|', $user->roles)
            ]);
            throw new NotAuthorizedException($request->user);
        }

        return $next($request);
    }
}
