<?php
/**
 * @author      Aurélien BERNARD - TRYDEA - 2020
 */

declare(strict_types=1);

namespace Shared\Authentication\EventListener;

use ApiPlatform\Core\Api\IriConverterInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Shared\Authentication\Entity\User;
use Symfony\Component\Serializer\SerializerInterface;

/**
 * Class AuthenticationSuccessListener.
 */
class AuthenticationSuccessListener
{
    /**
     * @var SerializerInterface
     */
    private $serializer;

    /**
     * @var IriConverterInterface
     */
    private $iriConverter;

    /**
     * AuthenticationSuccessListener constructor.
     * @param SerializerInterface $serializer
     * @param IriConverterInterface $iriConverter
     */
    public function __construct(SerializerInterface $serializer, IriConverterInterface $iriConverter)
    {
        $this->serializer = $serializer;
        $this->iriConverter = $iriConverter;
    }

    public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event)
    {
        $data = $event->getData();
        $user = $event->getUser();

        if (!$user instanceof User) {
            return;
        }

        $data['@id'] = $this->iriConverter->getIriFromItem($user);

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