<?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\MessageHandler;

use Ferienpass\CmsBundle\Message\PasswordLinkCreated;
use Ferienpass\CmsBundle\Message\PasswordResetHelpRequested;
use Ferienpass\CmsBundle\Message\PasswordResetUnavailable;
use Ferienpass\CmsBundle\Message\ResetPassword as ResetPasswordCommand;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Repository\UserRepository;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\MessageBusInterface;
use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;

#[AsMessageHandler(bus: 'command.bus')]
class ResetPassword
{
    public function __construct(private readonly UserRepository $users, private readonly ResetPasswordHelperInterface $resetPasswordHelper, private readonly MessageBusInterface $eventBus, private readonly LoggerInterface $logger)
    {
    }

    public function __invoke(ResetPasswordCommand $message): void
    {
        /** @var User $user */
        $user = $this->users->findOneBy(['email' => $message->getEmail()]);
        if (null === $user) {
            // Every branch below records its outcome. The requester always sees
            // the same "check your e-mail" page, so without this the only way to
            // answer "why did I get no mail?" was to guess.
            $this->log('no_account', $message->getEmail());

            // No account for this address. Rather than stay silent, tell the
            // mailbox owner no account is linked to it so they can retry with
            // the right one. The HTTP response is identical to the found-account
            // case, so this stays enumeration-safe.
            $this->eventBus->dispatch(new PasswordResetHelpRequested($message->getEmail()));

            return;
        }

        // A passkey-only account has no password to reset. Issuing a reset token
        // would let anyone controlling the mailbox *add* a password and take the
        // account over — re-introducing exactly the e-mail-takeover risk that
        // passkeys remove. Send an informational mail instead. The HTTP response
        // is identical either way, so the account's auth method never leaks
        // (enumeration-safe).
        if (null === $user->getPassword()) {
            $this->log('passkey_only', $message->getEmail(), $user);
            $this->eventBus->dispatch(new PasswordResetUnavailable((string) $user->getUuid()));

            return;
        }

        try {
            $resetToken = $this->resetPasswordHelper->generateResetToken($user);
        } catch (ResetPasswordExceptionInterface $e) {
            // Most often the bundle's throttle (one request per hour by
            // default). Nothing is sent, and the requester is told to check
            // their inbox — so a user who missed the first mail and tries again
            // gets silence. Record it rather than swallowing it.
            $this->log('throttled', $message->getEmail(), $user, ['reason' => $e->getReason()]);

            return;
        }

        $this->log('sent', $message->getEmail(), $user);

        $this->eventBus->dispatch(new PasswordLinkCreated((string) $user->getUuid(), $resetToken->getToken()));
    }

    private function log(string $outcome, string $email, ?User $user = null, array $context = []): void
    {
        $this->logger->info('Password reset requested: {outcome}', array_merge([
            'outcome' => $outcome,
            'email' => $email,
            'user' => $user?->getUuid()?->toRfc4122(),
            'scope' => 'cms',
        ], $context));
    }
}
