<?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\User;
use Ferienpass\CoreBundle\Message\AccountDisabled as AccountDisabledEvent;
use Ferienpass\CoreBundle\Notifier\Notifier;
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 AccountDisabled
{
    public function __construct(private readonly Notifier $notifier, private readonly UserRepository $users, private readonly UrlGeneratorInterface $urlGenerator, private readonly UriSigner $uriSigner)
    {
    }

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

        $notification = $this->notifier->accountCreated($user);
        if (!$notification instanceof \Ferienpass\CoreBundle\Notification\AccountCreatedNotification || '' === $email = (string) $user->getEmail()) {
            return;
        }

        $this->notifier->send(
            $notification->belongsTo($uuid)->actionUrl($this->uriSigner->sign($this->urlGenerator->generate('cms_registration_confirm', ['uuid' => $user->getUuid(), 'valid' => new \DateTimeImmutable('+3 days')->format('c')], UrlGeneratorInterface::ABSOLUTE_URL))),
            new Recipient($email)
        );
    }
}
