<?php

namespace App\Http\Middleware;

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

class ImpersonationMiddleware {
    public function handle(Request $request, Closure $next): Response {
        if ($request->session()->has('impersonator_id') && $request->session()->has('impersonated_id')) {
            $impersonatedId = $request->session()->get('impersonated_id');


            if ($impersonatedId && (!Auth::check() || Auth::id() !== $impersonatedId)) {
                Auth::loginUsingId($impersonatedId);
            }
        }


        return $next($request);
    }
}