<?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\NotificationHandler;

use Ferienpass\CoreBundle\Entity\Offer\OfferInterface;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Export\ParticipantList\PdfExport;
use Ferienpass\CoreBundle\Message\SendParticipantList as SendParticipantListEvent;
use Ferienpass\CoreBundle\Notification\ParticipantListNotification;
use Ferienpass\CoreBundle\Notifier\Notifier;
use Ferienpass\CoreBundle\Repository\OfferRepositoryInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Notifier\Recipient\Recipient;
use Symfony\Component\Uid\Uuid;

#[AsMessageHandler(bus: 'command.bus')]
class SendParticipantList
{
    public function __construct(private readonly Notifier $notifier, private readonly OfferRepositoryInterface $offers, private readonly PdfExport $pdfExport)
    {
    }

    public function __invoke(SendParticipantListEvent $event, Uuid $uuid): void
    {
        /** @var OfferInterface|null $offer */
        $offer = $this->offers->findOneBy(['uuid' => $event->getOfferId()]);
        if (null === $offer) {
            return;
        }

        $notification = $this->notifier->participantList($offer);
        if (!$notification instanceof ParticipantListNotification) {
            return;
        }

        // Generate both PDFs once and attach them to every recipient's mail.
        $participantList = $this->pdfExport->generate($offer, expanded: true);
        $attendanceList = $this->pdfExport->generate($offer, expanded: false);
        $notification->lists($participantList, $attendanceList);

        /** @var User $user */
        foreach ($offer->getParticipantListRecipients() as $user) {
            $email = $user->getEmail();
            if ('' === (string) $email) {
                continue;
            }

            $this->notifier->send($notification->belongsTo($uuid), new Recipient($email));
        }
    }
}
