<?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\Entity\User;
use Ferienpass\CoreBundle\Notification\UserPasswordNotification;
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;
use Symfony\Contracts\Translation\TranslatorInterface;

#[AsMessageHandler(bus: 'event.bus')]
class PasswordLink
{
    public function __construct(
        private readonly Notifier $notifier,
        private readonly UserRepository $users,
        private readonly UrlGeneratorInterface $urlGenerator,
        private readonly UserPasswordNotification $defaultNotification,
        private readonly TranslatorInterface $translator,
    ) {
    }

    public function __invoke(PasswordLinkCreated $event, Uuid $uuid): void
    {
        $user = $this->users->findOneBy(['uuid' => $event->getUserUuid()]);
        if (!$user instanceof User || null === $email = $user->getEmail()) {
            return;
        }

        // Prefer a DB-configured notification; otherwise fall back to the
        // built-in default content so the mail always sends (like the
        // login-link / passkey-notice mails). Returning early here used to make
        // a tenant with no — or a disabled — `user_password` notification row
        // drop *every* password reset silently: the requester saw the usual
        // "check your e-mail" page and nothing was ever sent.
        $notification = $this->notifier->userPassword($event->getToken(), $user);
        if (!$notification instanceof UserPasswordNotification) {
            $notification = (clone $this->defaultNotification)
                ->token($event->getToken())
                ->user($user)
                ->subject($this->translator->trans('defaults.user_password.emailSubject', [], 'notifications'))
                ->content($this->translator->trans('defaults.user_password.emailText', [], 'notifications'))
            ;
        }

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