<?php

namespace App\Http\Middleware;

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

class EnsureRole
{
    /**
     * Handle an incoming request.
     *
      * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next, string ...$roles): Response
    {
        $user = $request->user();

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

        if (empty($roles)) {
            return $next($request);
        }

        $roleName = $user->role?->slug ?? $user->role?->name;

        foreach ($roles as $role) {
            if (Str::lower((string) $roleName) === Str::lower($role)) {
                return $next($request);
            }
        }

        abort(403, 'You do not have permission to access this area.');

        return $next($request);
    }
}
