<?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\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 || null === $user->getEmail()) {
            return;
        }

        // Magic links are denied for this account: send a short explanatory mail
        // (no login link) so the recipient knows why nothing arrived and which
        // other methods (password / passkey) to use.
        if (null !== $reason = $event->getDeniedReason()) {
            $contentKey = LoginLinkRequested::DENIED_FOR_ADMIN === $reason
                ? 'signIn.magicLink.email.disabledForAdminContent'
                : 'signIn.magicLink.email.disabledByUserContent';

            $this->notifier->send(
                (clone $this->loginLinkNotification)
                    ->user($user)
                    ->subject($this->translator->trans('signIn.magicLink.email.disabledSubject', [], 'admin'))
                    ->content($this->translator->trans($contentKey, [], 'admin'))
                    ->belongsTo($uuid),
                new Recipient($user->getEmail())
            );

            return;
        }

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