<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\MessageHandler;

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Message\DeleteUserAccount as DeleteUserAccountCommand;
use Ferienpass\CoreBundle\Message\ReorderParticipantList;
use Ferienpass\CoreBundle\Repository\UserRepository;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Messenger\Stamp\DispatchAfterCurrentBusStamp;

#[AsMessageHandler(bus: 'command.bus')]
class DeleteUserAccount
{
    public function __construct(private readonly MessageBusInterface $eventBus, private readonly UserRepository $users, private readonly EntityManagerInterface $em)
    {
    }

    public function __invoke(DeleteUserAccountCommand $command): void
    {
        /** @var User $user */
        $user = $this->users->findOneBy(['uuid' => $command->getUserId()]);
        if (null === $user) {
            return;
        }

        $offers = [];
        foreach ($user->getParticipants() as $participant) {
            foreach ($participant->getAttendances() as $attendance) {
                $offers[] = (string) $attendance->getOffer()->getUuid();

                $this->em->remove($attendance);
            }

            $this->em->remove($participant);
        }

        $this->em->remove($user);

        foreach ($offers as $offerId) {
            $event = new ReorderParticipantList((string) $offerId);
            $this->eventBus->dispatch(
                new Envelope($event)
                    ->with(new DispatchAfterCurrentBusStamp())
            );
        }
    }
}
