<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;

class ImpersonateSanctum extends Middleware
{
    #[\Override]
    public function handle($request, Closure $next, ...$guards)
    {
        if ($request->attributes->get('sanctum') !== true) {
            // not a sanctum request
            return $next($request);
        }

        // logs a user in the WEB guard
        if ($request->hasSession() && $request->session()->has('impersonate')) {
            Auth::guard('web')->onceUsingId($request->session()->get('impersonate'));
        }

        return $next($request);
    }
}
