<?php

declare(strict_types=1);

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\AuthBundle\Command;

use Serenity\AuthBundle\Enum\ResetPasswordType;
use Serenity\AuthBundle\Query\UserAdminByEmailQuery;
use Serenity\AuthBundle\Query\UserByEmailQuery;
use Serenity\CoreBundle\Notification\Command\NotificationCommand;
use Serenity\CoreBundle\Notification\Enum\PushLevel;
use Serenity\CoreBundle\Shared\Messenger\Messaging\QueryBusInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;

#[AsMessageHandler]
final readonly class ResetPasswordCommandHandler
{
    public function __construct(private QueryBusInterface $queryBus,
        private ResetPasswordHelperInterface $resetPasswordHelper,
        private MessageBusInterface $commandBus,
        private TranslatorInterface $translator)
    {
    }

    public function __invoke(ResetPasswordCommand $command): void
    {
        if (ResetPasswordType::ADMIN === $command->resetPasswordType) {
            $user = $this->queryBus->ask(new UserAdminByEmailQuery($command->email));
        } else {
            $user = $this->queryBus->ask(new UserByEmailQuery($command->email));
        }

        if (!$user) {
            return;
        }

        try {
            $resetToken = $this->resetPasswordHelper->generateResetToken($user);
        } catch (ResetPasswordExceptionInterface $e) {
            $notification = new NotificationCommand(
                message: $this->translator->trans('security.reset_password.token_generator_failure', [], 'serenity_auth_messages'),
                level: PushLevel::ERROR
            );
            $this->commandBus->dispatch($notification);

            return;
        }
    }
}
