<?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\AdminBundle\NotificationHandler;

use Ferienpass\AdminBundle\Message\HostInvited as HostInvitedEvent;
use Ferienpass\CoreBundle\Entity\Host;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Notifier\Notifier;
use Ferienpass\CoreBundle\Repository\HostRepository;
use Ferienpass\CoreBundle\Repository\UserRepository;
use Symfony\Component\HttpFoundation\UriSigner;
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 HostInvitation
{
    public function __construct(private readonly Notifier $notifier, private readonly HostRepository $hosts, private readonly UserRepository $users, private readonly UrlGeneratorInterface $urlGenerator, private readonly UriSigner $uriSigner)
    {
    }

    public function __invoke(HostInvitedEvent $event, Uuid $uuid): void
    {
        /** @var User|null $user */
        $user = $this->users->findOneBy(['uuid' => $event->getUserUuid()]);
        /** @var Host|null $host */
        $host = $this->hosts->findOneBy(['uuid' => $event->getHostUuid()]);
        if (null === $user || null === $host) {
            return;
        }

        $notification = $this->notifier->userInvitation($user, $host, $event->getInviteeEmail());
        if (!$notification instanceof \Ferienpass\CoreBundle\Notification\UserInvitationNotification) {
            return;
        }

        $this->notifier->send(
            $notification->belongsTo($uuid)->actionUrl($this->uriSigner->sign($this->urlGenerator->generate('admin_invitation', ['email' => $event->getInviteeEmail(), 'host' => $host->getAlias()], UrlGeneratorInterface::ABSOLUTE_URL))),
            new Recipient($event->getInviteeEmail())
        );
    }
}
