<?php

namespace App\Http\Middleware;

use App\Enums\UserRole;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserHasRole
{
    /**
     * ثبت در bootstrap/app.php:
     * ->withMiddleware(function (Middleware $middleware) {
     *     $middleware->alias(['role' => \App\Http\Middleware\EnsureUserHasRole::class]);
     * })
     *
     * استفاده در routes: Route::middleware('role:admin')->group(...)
     * برای چند نقش: Route::middleware('role:admin,coach')->group(...)
     */
    public function handle(Request $request, Closure $next, string ...$roles): Response
    {
        $user = $request->user();

        abort_if(! $user, 401);

        $allowed = collect($roles)
            ->map(fn (string $r) => UserRole::from($r))
            ->contains($user->role);

        abort_unless($allowed, 403, 'شما اجازه‌ی دسترسی به این بخش را ندارید.');

        return $next($request);
    }
}
