<?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\Attendance;
use Ferienpass\CoreBundle\Message\RemindAttendance as RemindAttendanceEvent;
use Ferienpass\CoreBundle\Notification\RemindAttendanceNotification;
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: 'command.bus')]
class RemindAttendance
{
    public function __construct(private readonly Notifier $notifier, private readonly AttendanceRepository $attendances, private readonly PhoneFormatter $phone)
    {
    }

    public function __invoke(RemindAttendanceEvent $event, Uuid $uuid): void
    {
        /** @var list<Attendance> $attendances */
        $attendances = $this->attendances->findBy(['uuid' => $event->getAttendanceIds()]);
        if ([] === $attendances) {
            return;
        }

        // Every attendance in the message shares the same recipient (that is how
        // the cron grouped them); pick the first that actually resolves one.
        $recipient = null;
        foreach ($attendances as $attendance) {
            if ('' !== $email = (string) $attendance->getParticipant()?->getEmail()) {
                $recipient = new Recipient($email, (string) $this->phone->format($attendance->getParticipant()?->getMobile()));
                break;
            }
        }

        if (null === $recipient) {
            return;
        }

        $notification = $this->notifier->remindAttendance(...$attendances);
        if (!$notification instanceof RemindAttendanceNotification) {
            return;
        }

        $this->notifier->send($notification->belongsTo($uuid), $recipient);
    }
}
