<?php

namespace App\Components;

use App\Services\HistoryService;
use Livewire\Component;

class ExitImpersonation extends Component {
    public function render() {
        return view('components.exit-impersonation');
    }

    public function exit(HistoryService $history): void {
        if (!session()->has('impersonator_id')) {
            return;
        }


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

        // Record against the impersonated user, attributed to the resuming admin,
        // before switching the authenticated user back.
        $impersonatedUser = auth()->user();
        if ($impersonatedUser) {
            $history->add($impersonatedUser, 'Impersonation ended', [
                'impersonator_id' => $impersonatorId,
            ], $impersonatorId);
        }

        auth()->loginUsingId($impersonatorId);


        $this->redirectRoute('admin.users.index');
    }
}
