<?php

namespace App\Http\Middleware;

use App\Classes\ValueObjects\Constants\RoleTypes;
use Closure;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;

class EnsureUserIsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $maintenanceTitle = env('MAINTENANCE_MESSAGE_TITLE', null);
        if (!empty($maintenanceTitle)) {
            $user = JWTAuth::parseToken()->authenticate();
            if(!in_array($user->type, RoleTypes::ADMIN_ROLES)){
                return response()->view('errors.503', [], 503);
            }
        }
        return $next($request);
    }
}
