<?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\AttendanceStatusChanged;
use Ferienpass\CoreBundle\Notification\AttendanceNewlyConfirmedNotification;
use Ferienpass\CoreBundle\Notification\AttendanceNotificationChecker;
use Ferienpass\CoreBundle\Notifier\Notifier;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use Ferienpass\CoreBundle\Routing\OfferReaderUrl;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Notifier\Recipient\Recipient;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Uid\Uuid;

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

    public function __invoke(AttendanceStatusChanged $event, Uuid $uuid): void
    {
        if (!$event->shallNotify()) {
            return;
        }

        /** @var Attendance $attendance */
        $attendance = $this->attendances->findOneBy(['uuid' => $event->getAttendanceId()]);
        if (null === $attendance || !$attendance->isConfirmed() || !$this->notificationChecker->shouldNotify($attendance->getStatus(), false)) {
            return;
        }

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

        try {
            $notification->actionUrl($this->urlGenerator->generate('cms', ['to' => 'offer_list', 'auto_item' => OfferReaderUrl::autoItem($attendance->getOffer())], UrlGeneratorInterface::ABSOLUTE_URL));
        } catch (\InvalidArgumentException) {
        }

        $this->notifier->send($notification->belongsTo($uuid), new Recipient($email, (string) $this->phone->format($attendance->getParticipant()?->getMobile())));
    }
}
