<?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 IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @return mixed
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (Auth::check() && Auth::user()->hasRole(UserRole::ADMINISTRATOR)) {
            return $next($request);
        }

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

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