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

use Ferienpass\AdminBundle\Message\PasswordLinkCreated;
use Ferienpass\AdminBundle\Message\PasswordResetUnavailable;
use Ferienpass\AdminBundle\Message\ResetPassword as ResetPasswordCommand;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Repository\UserRepository;
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)
    {
    }

    public function __invoke(ResetPasswordCommand $message): void
    {
        /** @var User $user */
        $user = $this->users->findOneBy(['email' => $message->getEmail()]);
        if (null === $user) {
            return;
        }

        // A passkey-only admin has no password to reset. Issuing a reset token
        // would let anyone controlling the mailbox *add* a password and take the
        // account over — exactly the "single mailbox compromise = full account
        // takeover" scenario that SecurityController::removePassword() guards
        // against. 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->eventBus->dispatch(new PasswordResetUnavailable((string) $user->getUuid()));

            return;
        }

        try {
            $resetToken = $this->resetPasswordHelper->generateResetToken($user);
        } catch (ResetPasswordExceptionInterface) {
            return;
        }

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