<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserHasRole
{
    public function handle(Request $request, Closure $next, string $role): Response
    {
        $user = $request->user();
        $allowed = $user && ($user->role === $role || ($role === 'admin' && $user->role === 'super_admin'));

        if (! $allowed) {
            if ($user && Route::has($user->portalRole().'.dashboard')) {
                return redirect()->route($user->portalRole().'.dashboard')->with('status', 'Please switch to the correct demo account to open that portal.');
            }

            abort(403);
        }

        return $next($request);
    }
}
