<?php

namespace App\Http\Controllers;

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

class ImpersonationController extends Controller
{
    public function start(User $user): RedirectResponse
    {
        if ($user->id === auth()->id()) {
            return back()->with('error', 'You cannot impersonate yourself.');
        }

        if ($user->isAdmin()) {
            return back()->with('error', 'Cannot impersonate another admin.');
        }

        session(['impersonator_id' => auth()->id()]);

        Auth::loginUsingId($user->id);

        return redirect()->route('dashboard')
            ->with('success', 'Now viewing as '.$user->name.'.');
    }

    public function stop(Request $request): RedirectResponse
    {
        $impersonatorId = session('impersonator_id');

        if (! $impersonatorId) {
            return redirect()->route('dashboard');
        }

        Auth::loginUsingId($impersonatorId);
        $request->session()->forget('impersonator_id');

        return redirect()->route('users.index')
            ->with('success', 'Impersonation ended. You are back as yourself.');
    }
}
