<?php

namespace App\Http\Middleware;

use App\Enums\RoleSlug;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserHasRole
{
    /**
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next, string ...$roles): Response
    {
        $user = $request->user();
        $required = RoleSlug::wrap($roles);

        abort_unless(
            $user instanceof User && $required !== [] && $user->hasAnyRole(...$required),
            403,
        );

        return $next($request);
    }
}
