<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\AuthBundle\EventListener;

use Doctrine\ORM\EntityManagerInterface;
use Serenity\AuthBundle\Domain\User\Model\User;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\Security\Http\Event\LoginSuccessEvent;

#[AsEventListener(event: LoginSuccessEvent::class, method: 'onLogin')]
final readonly class LoginListener
{
    public function __construct(private EntityManagerInterface $em)
    {
    }

    public function onLogin(LoginSuccessEvent $event): void
    {
        $user = $event->getUser();
        $event->getRequest()->getClientIp();
        if ($user instanceof User) {
            $ip = $event->getRequest()->getClientIp();
            if ($ip !== $user->getLastLoginIp()) {
                $user->setLastLoginIp($ip);
            }
            $user->setLastLoginAt(new \DateTime());
            $this->em->flush();
        }
    }
}
