<?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 Ferienpass\CoreBundle\Entity\SentEmail;
use Ferienpass\CoreBundle\Message\ResendMail as ResendMailCommand;
use Ferienpass\CoreBundle\Repository\SentEmailRepository;
use Symfony\Component\Mailer\Messenger\SendEmailMessage;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Mime\Email;

#[AsMessageHandler(bus: 'command.bus')]
class ResendMail
{
    public function __construct(private readonly SentEmailRepository $repository, private readonly MessageBusInterface $bus)
    {
    }

    public function __invoke(ResendMailCommand $command): void
    {
        $sentEmail = $this->repository->find($command->getMessageId());
        if (!$sentEmail instanceof SentEmail || null === $sentEmail->getTo()) {
            return;
        }

        $email = new Email()
            ->to($sentEmail->getTo())
            ->subject((string) $sentEmail->getSubject())
        ;

        if (null !== $sentEmail->getFrom()) {
            $email->from($sentEmail->getFrom());
        }
        if (null !== $sentEmail->getReplyTo()) {
            $email->replyTo($sentEmail->getReplyTo());
        }
        if ($sentEmail->getHtml()) {
            $email->html($sentEmail->getHtml());
        }
        if ($sentEmail->getText()) {
            $email->text($sentEmail->getText());
        }

        $this->bus->dispatch(new SendEmailMessage($email));
    }
}
