<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\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
    {
        if ($user->isAdmin()) {
            return redirect()
                ->back()
                ->with('error', 'Cannot impersonate admin users.');
        }

        AuditLog::query()->create([
            'user_id' => $user->id,
            'admin_id' => $request->user()->id,
            'action' => 'impersonate_start',
            'resource_type' => 'User',
            'resource_id' => $user->id,
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'changes' => [
                'admin' => $request->user()->name,
                'customer' => $user->name,
            ],
        ]);

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

        Auth::login($user);

        return redirect()->away('https://'.config('app.domains.account').'/dashboard')
            ->with('info', "You are now impersonating {$user->name}.")
            ->with('success', "Impersonation started. You are now viewing as {$user->name}.");
    }

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

        if (! $impersonatorId) {
            return redirect()->back();
        }

        $admin = User::find($impersonatorId);

        if (! $admin) {
            return redirect()->back()->with('error', 'Original admin user not found.');
        }

        $request->session()->forget('impersonator_id');

        Auth::login($admin);

        return redirect('https://'.config('app.domains.admin').'/dashboard')
            ->with('success', 'Impersonation ended.');
    }
}
