<?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\Host;
use Ferienpass\CoreBundle\Entity\Offer\OfferInterface;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Message\OfferCompleteNotify as OfferCompleteEvent;
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;

#[AsMessageHandler(bus: 'event.bus')]
class OfferComplete
{
    public function __construct(private readonly Notifier $notifier, private readonly OfferRepositoryInterface $offers, private readonly UrlGeneratorInterface $urlGenerator)
    {
    }

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

        $notification = $this->notifier->offerComplete($offer);
        if (!$notification instanceof \Ferienpass\CoreBundle\Notification\OfferCompleteNotification) {
            return;
        }

        /** @var Host $host */
        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($this->urlGenerator->generate('admin_offers_complete', ['uuid' => $offer->getUuid()->toBase58()], UrlGeneratorInterface::ABSOLUTE_URL)),
                    new Recipient($email)
                );
            }
        }
    }
}
