<?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\LoginLinkRequested;
use Ferienpass\CoreBundle\Notification\UserLoginLinkNotification;
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\Uid\Uuid;
use Symfony\Contracts\Translation\TranslatorInterface;

#[AsMessageHandler(bus: 'event.bus')]
class LoginLink
{
    public function __construct(private readonly Notifier $notifier, private readonly UserRepository $users, private readonly UserLoginLinkNotification $loginLinkNotification, private readonly TranslatorInterface $translator)
    {
    }

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

        // The member turned e-mail sign-in off: send a short explanatory mail
        // (no action URL — an explanation rather than a way in) instead of a
        // login link, so they know why nothing arrived and which other methods
        // (password / passkey) to use.
        if ($event->isDisabled()) {
            $this->notifier->send(
                (clone $this->loginLinkNotification)
                    ->user($user)
                    ->subject($this->translator->trans('signIn.magicLink.email.disabledSubject', [], 'cms'))
                    ->content($this->translator->trans('signIn.magicLink.email.disabledContent', [], 'cms'))
                    ->belongsTo($uuid),
                new Recipient($user->getEmail())
            );

            return;
        }

        $this->notifier->send(
            (clone $this->loginLinkNotification)
                ->user($user)
                ->subject($this->translator->trans('signIn.magicLink.email.subject', [], 'cms'))
                ->content($this->translator->trans('signIn.magicLink.email.content', [], 'cms'))
                ->belongsTo($uuid)
                ->actionUrl($event->getLoginLink()),
            new Recipient($user->getEmail())
        );
    }
}
