<?php

namespace App\Http\Middleware;

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

class IsModerator
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (Auth::check() && (
            Auth::user()->hasRole(UserRole::MODERATOR) ||
            Auth::user()->hasRole(UserRole::ADMINISTRATOR))) {
            return $next($request);
        }

        session()->flash('error_msg', 'This resource is restricted to Moderators!');

        return redirect()->route('home.index');
    }
}
