<?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\OfferRelaunched as OfferRelaunchedEvent;
use Ferienpass\CoreBundle\Notification\OfferRelaunchedNotification;
use Ferienpass\CoreBundle\Notifier\Notifier;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Notifier\Recipient\Recipient;
use Symfony\Component\Uid\Uuid;

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

    public function __invoke(OfferRelaunchedEvent $event, Uuid $uuid): void
    {
        $attendance = $this->attendances->findOneBy(['uuid' => $event->getAttendanceId()]);

        $notification = $this->notifier->offerRelaunched($attendance);
        if (!$notification instanceof OfferRelaunchedNotification || '' === $email = (string) $attendance->getParticipant()?->getEmail()) {
            return;
        }

        if ($event->getNotifyText()) {
            $notification->content($event->getNotifyText());
        }

        // Todo if not reactive participants then discard attendances
        $this->notifier->send($notification->belongsTo($uuid), new Recipient($email, (string) $this->phone->format($attendance->getParticipant()?->getMobile())));
    }
}
