<?php

namespace App\Components\Admin\Users;

use App\Models\User\User;
use App\Services\HistoryService;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class ImpersonateUser extends Component {
    public User $user;

    public function impersonate(HistoryService $history) {
        $this->authorize('impersonate', $this->user);

        $impersonatorId = Auth::id();

        session([
            'impersonator_id' => $impersonatorId,
        ]);

        // Record before switching the authenticated user so the entry is
        // attributed to the impersonating admin, not the impersonated user.
        $history->add($this->user, 'Impersonation started', [
            'impersonator_id' => $impersonatorId,
        ], $impersonatorId);

        Auth::login($this->user);

        return redirect()->route('dashboard');
    }

    public function render() {
        return view('components.admin.users.impersonate-user');
    }
}
