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

use Ferienpass\CmsBundle\Message\PasswordLinkCreated;
use Ferienpass\CoreBundle\Notifier\Notifier;
use Ferienpass\CoreBundle\Repository\UserRepository;
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 PasswordLink
{
    public function __construct(private readonly Notifier $notifier, private readonly UserRepository $users, private readonly UrlGeneratorInterface $urlGenerator)
    {
    }

    public function __invoke(PasswordLinkCreated $event, Uuid $uuid): void
    {
        $user = $this->users->findOneBy(['uuid' => $event->getUserUuid()]);

        $notification = $this->notifier->userPassword($event->getToken(), $user);
        if (!$notification instanceof \Ferienpass\CoreBundle\Notification\UserPasswordNotification) {
            return;
        }

        $this->notifier->send(
            $notification->belongsTo($uuid)->actionUrl($this->urlGenerator->generate('cms_lost_password_reset', ['token' => $event->getToken()], UrlGeneratorInterface::ABSOLUTE_URL)),
            new Recipient($user->getEmail())
        );
    }
}
