<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class BlockAdminDuringImpersonation
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Allow the stop impersonation route
        if ($request->routeIs('admin.impersonate.stop')) {
            return $next($request);
        }

        // Block admin routes during impersonation
        if (session()->has('impersonating_from')) {
            return redirect()
                ->route('user.apps')
                ->with('toast', [
                    'type' => 'warning',
                    'message' => __('admin.admin_blocked_during_impersonation'),
                ]);
        }

        return $next($request);
    }
}
