<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Service\Mailer;

use Psr\Log\LoggerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\Envelope;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\BodyRendererInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\RawMessage;

class ChillMailer implements MailerInterface
{
    private string $prefix = '[Chill] ';

    public function __construct(private readonly MailerInterface $initial, private readonly LoggerInterface $chillLogger, private readonly BodyRendererInterface $bodyRenderer) {}

    public function send(RawMessage $message, ?Envelope $envelope = null): void
    {
        if ($message instanceof Email) {
            $message->subject($this->prefix.$message->getSubject());
        }

        if ($message instanceof TemplatedEmail) {
            $this->bodyRenderer->render($message);
        }

        $this->chillLogger->info('chill email sent', [
            'to' => array_map(static fn (Address $address) => $address->getAddress(), $message->getTo()),
            'subject' => $message->getSubject(),
        ]);

        $this->initial->send($message, $envelope);
    }
}
