<?php

namespace App\Http\Middleware;

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

class EnsureRole
{
    public function handle(Request $request, Closure $next, string ...$roles): Response
    {
        $user = $request->user();

        if (!$user) {
            abort(401);
        }

        $allowed = array_map(static fn (string $role): string => strtolower($role), $roles);

        if (!in_array(strtolower((string) $user->role), $allowed, true)) {
            abort(403, 'Forbidden');
        }

        return $next($request);
    }
}
