<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\ImpersonationException;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\ImpersonationService;
use Illuminate\Http\RedirectResponse;

class ImpersonationController extends Controller
{
    public function __construct(
        protected ImpersonationService $impersonationService
    ) {}

    /**
     * Start impersonating a user.
     */
    public function start(User $user): RedirectResponse
    {
        // Block in demo mode
        if (config('app.demo')) {
            abort(403, __('admin.impersonation_disabled_demo'));
        }

        $admin = auth()->user();

        // Ensure current user is admin
        if (! $admin->isAdmin()) {
            abort(403, __('admin.only_admins_can_impersonate'));
        }

        try {
            $this->impersonationService->start($admin, $user);

            return redirect()
                ->route('user.apps')
                ->with('toast', [
                    'type' => 'success',
                    'message' => __('admin.impersonation_started', ['name' => $user->name]),
                ]);
        } catch (ImpersonationException $e) {
            abort(403, $e->getMessage());
        }
    }

    /**
     * Stop impersonating and return to admin.
     */
    public function stop(): RedirectResponse
    {
        $result = $this->impersonationService->stop();

        if (! $result) {
            return redirect()
                ->back()
                ->with('toast', [
                    'type' => 'error',
                    'message' => __('admin.not_impersonating'),
                ]);
        }

        return redirect()
            ->route('admin.users')
            ->with('toast', [
                'type' => 'success',
                'message' => __('admin.impersonation_stopped'),
            ]);
    }
}
