<?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\Doctrine\Repository\UserRepository;
use Serenity\AuthBundle\Domain\User\Exception\NoUniqueUserException;
use Serenity\AuthBundle\Domain\User\Model\User;
use Serenity\AuthBundle\Query\UserAdminByEmailQuery;
use Serenity\CoreBundle\Shared\Common\UserInterface;
use Serenity\CoreBundle\Shared\Messenger\Messaging\QueryBusInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
final readonly class CreateUserCommandHandler
{
    public function __construct(private QueryBusInterface $queryBus, private UserRepository $userRepository)
    {
    }

    public function __invoke(CreateUserCommand $command): UserInterface
    {
        if ($this->queryBus->ask(new UserAdminByEmailQuery($command->email))) {
            throw new NoUniqueUserException($command->email);
        }
        $user = new User(
            $command->email,
            $command->plainPassword,
            $command->roles,
            $command->test
        );

        $this->userRepository->save($user);

        return $user;
    }
}
