<?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\UnblockEmail as UnblockEmailCommand;
use Ferienpass\CoreBundle\Repository\BlockedContactRepository;
use Ferienpass\CoreBundle\Repository\UserRepository;
use GuzzleHttp\Exception\ClientException;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Contracts\HttpClient\HttpClientInterface;

#[AsMessageHandler(bus: 'command.bus')]
class UnblockEmail
{
    public function __construct(private readonly HttpClientInterface $brevoClient, private readonly UserRepository $users, private readonly BlockedContactRepository $blockedContacts, private readonly EntityManagerInterface $entityManager)
    {
    }

    public function __invoke(UnblockEmailCommand $command): void
    {
        $response = $this->brevoClient->request('DELETE', '/v3/smtp/blockedContacts/{email}', [
            'vars' => [
                'email' => $command->getEmail(),
            ],
        ]);

        try {
            $response->getContent(true);

            if (($blocked = $this->blockedContacts->findByEmail($command->getEmail())) instanceof BlockedContact) {
                $this->entityManager->remove($blocked);
            }

            if ($command->getUserId() && ($user = $this->users->findOneBy(['uuid' => $command->getUserId()])) && $user instanceof User) {
                $user->setBlockedEmail(false);
            }
        } catch (ClientException) {
        }
    }
}
