<?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\Message\DecisionLetterDispatched as DecisionLetterDispatchedEvent;
use Ferienpass\CoreBundle\Notification\AttendanceDecisions;
use Ferienpass\CoreBundle\Notifier\Notifier;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use Ferienpass\CoreBundle\Repository\EditionRepository;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Notifier\Recipient\Recipient;
use Symfony\Component\Uid\Uuid;

#[AsMessageHandler(bus: 'event.bus')]
class DecisionLetterDispatched
{
    public function __construct(private readonly Notifier $notifier, private readonly AttendanceRepository $attendances, private readonly EditionRepository $editions)
    {
    }

    public function __invoke(DecisionLetterDispatchedEvent $event, Uuid $uuid): void
    {
        $email = $event->getEmail();
        $attendances = $this->attendances->findBy(['uuid' => $event->getAttendanceIds()]);
        $edition = $this->editions->findOneBy(['uuid' => $event->getEditionId()]);

        $notification = $this->notifier->attendanceDecisions($attendances, $edition);
        if (!$notification instanceof AttendanceDecisions) {
            return;
        }

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