<?php

namespace App\EventListener;


use ApiPlatform\Metadata\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 => 5,
        ]);
        $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);
    }
}