<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Models\Role;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckIfAdminRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Check status
        if (auth()->user()->status == 'inactive') {
            $redirectUrl = auth()->user()->getRedirectRouteIfNotAuthenticated();
            auth()->logout();
            return redirect($redirectUrl);
        }

        // Check role
        $roles = [
            Role::IT_PERSONNEL_ROLE,
            Role::NUMSTATION_MANAGER_ROLE,
            Role::NUMSTATION_STAFF_ROLE,
        ];
        if (in_array(auth()->user()->role_id, $roles)) {
            return $next($request);
        }
        return abort(Response::HTTP_FORBIDDEN, '403 Access Forbidden');
    }
}
