<?php

namespace DMD\LaLigaApi\Service\User\Handlers\login;

use DMD\LaLigaApi\Dto\NotificationDto;
use DMD\LaLigaApi\Dto\UserDto;
use DMD\LaLigaApi\Entity\User;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Security\Core\User\UserInterface;

class AuthenticationSuccessListener
{
    public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event): void
    {
        $data = $event->getData();
        $userDto = new UserDto();
        $user = $event->getUser();
        if (!$user instanceof User)
        {
            throw new HttpException(500, 'Internal server error');
        }
        $notificationEntityList = $user->getReceivedNotifications(); // todo hacer query de notificaciones no leidas
        $notificationDtoList = [];
        if (!empty($notificationEntityList))
        {
            foreach ($notificationEntityList as $notificationEntity)
            {
                $notificationDto = new NotificationDto();
                $notificationDto->fillFromObj($notificationEntity);
                $notificationDtoList[] = $notificationDto;
            }
        }
        $userDto->receivedNotificationDtoList = $notificationDtoList;
        $userDto->fillFromObject($user);
        $expirationDateTime = (new \DateTime('now', new \DateTimeZone('Europe/Madrid')))->modify('+1800 seconds');
        $data['expirationDateTime'] = $expirationDateTime->format('Y-m-d H:i:s');
        $data['user'] = $userDto->toLoginArray();

        $event->setData($data);
    }
}