<?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\Message\ApplicationsClosed as ApplicationsClosedEvent;
use Ferienpass\CoreBundle\Notification\ApplicationsClosedNotification;
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\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Uid\Uuid;

/**
 * "Teilnahmeliste verfügbar" — the roster is ready now that applications have
 * closed. Triggered by {@see \Ferienpass\CoreBundle\Cron\NotifyApplicationsClosed}
 * once the deadline has passed and the event is still ahead.
 */
#[AsMessageHandler(bus: 'event.bus')]
class ApplicationsClosed
{
    public function __construct(private readonly Notifier $notifier, private readonly OfferRepositoryInterface $offers, private readonly UrlGeneratorInterface $urlGenerator)
    {
    }

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

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

        // The mail announces a roster and links straight to it, so it must not go
        // out while the edition still withholds participant lists — the host would
        // land on a 403. This cannot be an is_granted('participants.view') check:
        // the handler runs from a cron, where OfferVoter denies everything for want
        // of a logged-in user.
        if (true !== $offer->getEdition()?->isParticipantListReleased()) {
            return;
        }

        $viewUrl = $this->urlGenerator->generate('admin_offers_participants', ['uuid' => $offer->getUuid()->toBase58()], UrlGeneratorInterface::ABSOLUTE_URL);

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

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