<?php

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

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

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('+18000 seconds');
        $data['expirationDateTime'] = $expirationDateTime->format('Y-m-d H:i:s');
        $data['user'] = $userDto->toLoginArray();

        $customRoleCollection = $user->getCustomRoles();
        $relationshipArray = [];
        if (!is_null($customRoleCollection))
        {
            foreach ($customRoleCollection as $customRoleEntity)
            {
                $relationshipArray[] = [
                    'role' => $customRoleEntity->getName(),
                    'entityId' => $customRoleEntity->getEntityId()
                ];
            }
        }
        $data['relationships'] = $relationshipArray;
        $event->setData($data);
    }
}