<?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\Notification;

use Ferienpass\CoreBundle\Entity\Payment;
use Ferienpass\CoreBundle\Notifier\Mime\NotificationEmail;
use Symfony\Component\Mailer\Header\TagHeader;
use Symfony\Component\Notifier\Message\EmailMessage;
use Symfony\Component\Notifier\Notification\EmailNotificationInterface;
use Symfony\Component\Notifier\Recipient\EmailRecipientInterface;
use Symfony\Component\Notifier\Recipient\RecipientInterface;

class MailingNotification extends AbstractNotification implements EmailNotificationInterface
{
    private array $context = [];

    /** @var string[] */
    private array $attachments = [];

    private ?string $bcc = null;

    public function getChannels(RecipientInterface $recipient): array
    {
        return ['email'];
    }

    public function getContext(): array
    {
        return $this->context;
    }

    public function context(array $context): static
    {
        $this->context = $context;

        return $this;
    }

    public function attachments(array $attachments): static
    {
        $this->attachments = $attachments;

        return $this;
    }

    public function bcc(?string $bcc): static
    {
        $this->bcc = $bcc;

        return $this;
    }

    public function payment(Payment $payment, string $paymentUrl): static
    {
        $this->context['payment'] = $payment;
        $this->context['payment_url'] = $paymentUrl;

        return $this;
    }

    public static function getAvailableTokens(): array
    {
        return array_merge(parent::getAvailableTokens(), ['user', 'token']);
    }

    public function asEmailMessage(EmailRecipientInterface $recipient, ?string $transport = null): ?EmailMessage
    {
        $email = new NotificationEmail('mailing')
            ->to($recipient->getEmail())
            ->subject($this->getSubject())
            ->content($this->getContent())
            ->context($this->getContext())
            ->belongsTo($this->getBelongsTo()?->toRfc4122())
        ;

        if (null !== $this->getReplyTo()) {
            $email->replyTo($this->getReplyTo());
        }

        if (null !== $this->bcc) {
            $email->addBcc($this->bcc);
        }

        foreach ($this->attachments as $attachment) {
            if (!is_file($attachment)) {
                continue;
            }

            $email->attachFromPath($attachment);
        }

        $email->getHeaders()->add(new TagHeader('mailing'));

        return new EmailMessage($email);
    }
}
