<?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\EventListener\Mailer;

use Ferienpass\CoreBundle\Settings\MailConfigManager;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\Mailer\Event\MessageEvent;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;

#[AsEventListener]
class MailerConfigListener
{
    public function __construct(private readonly MailConfigManager $mailConfigManager)
    {
    }

    public function __invoke(MessageEvent $event): void
    {
        $message = $event->getMessage();
        if (!$message instanceof Email) {
            return;
        }

        if (null === $message->getFrom()) {
            if ($adminEmail = $this->mailConfigManager->getAdminEmail()) {
                $message->from(new Address($adminEmail, $this->mailConfigManager->getAdminEmailName() ?? 'Ferienpass Admin'));
            }
        }

        if (null === $message->getReplyTo()) {
            if ($replyTo = $this->mailConfigManager->getReplyTo()) {
                $message->replyTo(new Address($replyTo, $this->mailConfigManager->getReplyToName() ?? $this->mailConfigManager->getAdminEmailName() ?? 'Ferienpass Admin'));
            }
        }
    }
}
