<?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\Attendance;
use Ferienpass\CoreBundle\Message\DeleteAttendance as DeleteAttendanceCommand;
use Ferienpass\CoreBundle\Message\ReorderParticipantList;
use Ferienpass\CoreBundle\Message\UpdateParticipantPriorities;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Uid\Uuid;

#[AsMessageHandler(bus: 'command.bus')]
class DeleteAttendance
{
    public function __construct(private readonly AttendanceRepository $attendances, private readonly EntityManagerInterface $entityManager, private readonly MessageBusInterface $commandBus)
    {
    }

    public function __invoke(DeleteAttendanceCommand $command, Uuid $uuid): void
    {
        $attendance = $this->attendances->findOneBy(['uuid' => $command->getAttendanceId()]);
        if (!$attendance instanceof Attendance) {
            return;
        }

        $offerId = $attendance->getOffer()->getUuid();
        $participantId = $attendance->getParticipant()->getUuid();
        $editionId = $attendance->getOffer()->getEdition()->getUuid();

        $this->entityManager->remove($attendance);

        $this->commandBus->dispatch(new ReorderParticipantList((string) $offerId));
        $this->commandBus->dispatch(new UpdateParticipantPriorities((string) $participantId, (string) $editionId));
    }
}
