<?php

namespace Ignite\Core\Listeners;

use Ignite\Core\Auth\Impersonation;
use Illuminate\Log\Logger;

class StopIfImpersonating
{
    /**
     * @var Impersonation
     */
    private $impersonation;
    /**
     * @var Logger
     */
    private $logger;

    /**
     * StopIfImpersonating constructor.
     *
     * @param Impersonation $impersonation
     * @param Logger $logger
     */
    public function __construct(Impersonation $impersonation, Logger $logger)
    {
        $this->impersonation = $impersonation;
        $this->logger = $logger;
    }

    /**
     * Handle user login events.
     *
     * @param  \Illuminate\Auth\Events\Login $event
     */
    public function handle($event)
    {
        if ($this->impersonation->isImpersonating()) {
            try {
                $this->impersonation->stopImpersonating();
            } catch (\Exception $exception) {
                $this->logger->error("Unable to stop impersonating User ID: {$event->user->getKey()}");
            }
        }
    }
}
