<?php
declare(strict_types=1);

namespace App\Mailer;

final class PhpMailMailer implements MailerInterface
{
    public function __construct(
        private readonly string $fromEmail = '',
        private readonly string $fromName = 'Quaeriva',
    ) {
    }

    public function send(EmailMessage $message): void
    {
        $to = trim($message->to);
        if (filter_var($to, FILTER_VALIDATE_EMAIL) === false) return;

        $headers = [
            'MIME-Version: 1.0',
            'Content-Type: text/plain; charset=UTF-8',
        ];
        $fromEmail = trim($this->fromEmail);
        if ($fromEmail !== '' && filter_var($fromEmail, FILTER_VALIDATE_EMAIL) !== false) {
            $name = trim(preg_replace('/[\r\n]+/', ' ', $this->fromName) ?? $this->fromName);
            $headers[] = 'From: ' . ($name !== '' ? $name . ' <' . $fromEmail . '>' : $fromEmail);
            $headers[] = 'Reply-To: ' . $fromEmail;
        }
        $subject = trim(preg_replace('/[\r\n]+/', ' ', $message->subject) ?? $message->subject);
        if (function_exists('mb_encode_mimeheader')) {
            $subject = mb_encode_mimeheader($subject, 'UTF-8');
        }
        if (!mail($to, $subject, $message->body, implode("\r\n", $headers))) {
            throw new \RuntimeException('PHP mail transport rejected the message.');
        }
    }
}
