<?php

namespace App\Http\Controllers;

use App\Models\User\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ImpersonationController extends Controller {
    public function start(Request $request, User $user): RedirectResponse {
        $this->authorize('impersonate', $user);


        $request->session()->put('impersonator_id', Auth::id());
        $request->session()->put('impersonated_id', $user->id);


        Auth::login($user);


        return redirect('/')->with('success', 'Now impersonating ' . $user->email);
    }


    public function stop(Request $request, User $user): RedirectResponse {
        if (!$request->session()->has('impersonator_id')) {
            return redirect('/');
        }


        $impersonatorId = $request->session()->pull('impersonator_id');
        $request->session()->forget('impersonated_id');


        Auth::loginUsingId($impersonatorId);


        return redirect()->route('admin.users.index')->with('success', 'Exited impersonation.');
    }
}
