<?php
/**
 * @author Daniel Knudsen <d.knudsen@spawntree.de>
 * @date 18.01.24
 */


namespace App\EventListener;


use ApiPlatform\Api\IriConverterInterface;
use App\ApiResource\UserApi;
use App\Entity\User;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Symfonycasts\MicroMapper\MicroMapperInterface;

class AuthenticationSuccessListener
{
    public function __construct(
        private MicroMapperInterface $microMapper,
        private IriConverterInterface $iriConverter
    )
    {
    }

    /**
     * @param AuthenticationSuccessEvent $event
     */
    public function onAuthenticationSuccessResponse(
        AuthenticationSuccessEvent $event
    ): void
    {
        $data = $event->getData();
        $user = $event->getUser();

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

        $userApi = $this->microMapper->map($user, UserApi::class, [
            MicroMapperInterface::MAX_DEPTH => 1,
        ]);
        $userIri = $this->iriConverter->getIriFromResource($userApi);

        $data['id'] = $userIri;
        $data['email'] = $user->getEmail();
        $data['firstName'] = $user->getFirstName();
        $data['lastName'] = $user->getLastName();
        $data['roles'] = $user->getRoles();
        $data['userResource'] = $userApi;
        $event->setData($data);
    }
}