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

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CoreBundle\Entity\BlockedContact;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Message\BlockEmail as BlockEmailCommand;
use Ferienpass\CoreBundle\Repository\BlockedContactRepository;
use Ferienpass\CoreBundle\Repository\UserRepository;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'command.bus')]
class BlockEmail
{
    public function __construct(
        private readonly UserRepository $users,
        private readonly EntityManagerInterface $entityManager,
        #[Autowire(param: 'kernel.secret')]
        private readonly string $secret,
    ) {
    }

    public function __invoke(BlockEmailCommand $command): void
    {
        /** @var User|null $user */
        $user = $this->users->findOneBy(['email' => $command->getEmail()]);
        $user?->setBlockedEmail(true);

        $block = new BlockedContact(BlockedContactRepository::hashEmail($command->getEmail(), $this->secret), $user);

        $this->entityManager->persist($block);
    }
}
