<?php

declare(strict_types=1);

final class MyronMailer
{
    public function send(array $settings, string $toEmail, string $subject, string $htmlBody, string $textBody = ''): void
    {
        if (!function_exists('myronMailTransportRegistry')) {
            $capturePath = trim((string) (getenv('MYRON_MAIL_CAPTURE_PATH') ?: ''));
            if ($capturePath !== '') {
                $payload = [
                    'to' => $toEmail,
                    'from' => (string) ($settings['from_email'] ?? ''),
                    'fromName' => (string) ($settings['from_name'] ?? ''),
                    'subject' => $subject,
                    'text' => $textBody,
                    'html' => $htmlBody,
                    'capturedAt' => myronNow(),
                ];
                file_put_contents($capturePath, json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL, FILE_APPEND);
                return;
            }
            throw new RuntimeException('Mail transport registry is unavailable.');
        }
        $envelope = new MailEnvelope(
            to: $toEmail,
            subject: $subject,
            htmlBody: $htmlBody,
            textBody: $textBody,
            fromEmail: (string) ($settings['from_email'] ?? ''),
            fromName: (string) ($settings['from_name'] ?? ''),
        );
        $result = myronMailTransportRegistry()->activeTransport()->send($envelope);
        if (!$result->ok) {
            throw new RuntimeException($result->error ?? 'Mail dispatch failed.');
        }
    }
}
