<?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 Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Entity\Edition;
use Ferienpass\CoreBundle\Message\DecisionLetterDispatched;
use Ferienpass\CoreBundle\Message\DispatchDecisionLetters as DispatchDecisionLettersCommand;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use Ferienpass\CoreBundle\Repository\EditionRepository;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Messenger\Stamp\DispatchAfterCurrentBusStamp;
use Symfony\Component\Uid\Uuid;

#[AsMessageHandler(bus: 'command.bus')]
class DispatchDecisionLetters
{
    public function __construct(private readonly AttendanceRepository $attendances, private readonly EditionRepository $editions, private readonly MessageBusInterface $eventBus)
    {
    }

    public function __invoke(DispatchDecisionLettersCommand $command, Uuid $uuid): void
    {
        $edition = $this->editions->findOneBy(['uuid' => $command->getEditionId()]);
        if (!$edition instanceof Edition) {
            return;
        }

        $decisions = [];
        /** @var Attendance $attendance */
        foreach ($this->attendances->findBy(['uuid' => $command->getAttendanceIds()]) as $attendance) {
            $decisions[$attendance->getEmail()][] = $attendance;
        }

        foreach ($decisions as $email => $attendances) {
            $event = new DecisionLetterDispatched(
                $email,
                $command->getEditionId(),
                array_map(static fn (Attendance $a) => (string) $a->getUuid(), $attendances),
                (string) $uuid
            );

            $this->eventBus->dispatch(
                new Envelope($event)
                    ->with(new DispatchAfterCurrentBusStamp())
            );
        }
    }
}
