<?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\Message\SendMailing as SendMailingCommand;
use Ferienpass\CoreBundle\Notification\MailingNotification;
use Ferienpass\CoreBundle\Notifier\Notifier;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Notifier\Recipient\Recipient;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Uid\Uuid;

#[AsMessageHandler(bus: 'event.bus')]
class SendMailing
{
    public function __construct(private readonly Notifier $notifier, private readonly MailingNotification $mailingNotification, #[Autowire(param: 'ferienpass.reply_address')] private readonly ?string $replyTo, private readonly UrlGeneratorInterface $urlGenerator)
    {
    }

    public function __invoke(SendMailingCommand $command, Uuid $uuid): void
    {
        $context = $command->getContext();
        if ($command->isPersonalized()) {
            // Personalized delivery: resolve {{ recipientEmail }} to the actual
            // recipient. The non-personalized copy keeps the neutral sample
            // address that the caller placed in the context.
            $context['recipientEmail'] = $command->getEmail();
        }

        $notification = (clone $this->mailingNotification)
            ->subject($command->getSubject())
            ->content($command->getContent())
            ->attachments($command->getAttachments())
            ->context($context)
        ;

        if (null !== $command->getBcc()) {
            $notification->bcc($command->getBcc());
        }

        if ($this->replyTo) {
            $notification->replyTo($this->replyTo);
        }

        if ($command->getPayment() instanceof \Ferienpass\CoreBundle\Entity\Payment) {
            $paymentUrl = $this->urlGenerator->generate('cms_pay', ['token' => $command->getPayment()->getUuid()], UrlGeneratorInterface::ABSOLUTE_URL);

            $notification->payment($command->getPayment(), $paymentUrl);
        }

        $this->notifier->send($notification->belongsTo($uuid), new Recipient($command->getEmail()));
    }
}
