<?php

declare(strict_types=1);

final class MyronMailTestService
{
    public function __construct(
        private readonly MyronMailSettingsRepository $mailSettings,
        private readonly MyronMailer $mailer,
    ) {
    }

    public function sendToConfiguredAddress(): string
    {
        if (!$this->mailSettings->isConfigured()) {
            throw new RuntimeException('Save complete mail settings before sending a test email.');
        }

        $settings = $this->mailSettings->getSettings();
        if (!is_array($settings)) {
            throw new RuntimeException('Save complete mail settings before sending a test email.');
        }

        $recipientEmail = myronNormalizeEmail((string) ($settings['from_email'] ?? ''));
        if (!filter_var($recipientEmail, FILTER_VALIDATE_EMAIL)) {
            throw new RuntimeException('Save a valid From Email address before sending a test email.');
        }

        $fromName = trim((string) ($settings['from_name'] ?? ''));
        $subject = 'MyronCMS mail settings test';
        $textBody = implode("\n", [
            'This is a MyronCMS test email.',
            '',
            'Recipient: ' . $recipientEmail,
            'Mailbox: ' . ($fromName !== '' ? $fromName : 'Configured sender'),
            'Sent at: ' . myronNow(),
        ]);
        $htmlBody = '<p>This is a <strong>MyronCMS</strong> test email.</p>'
            . '<p><strong>Recipient:</strong> ' . myronEscape($recipientEmail) . '<br>'
            . '<strong>Mailbox:</strong> ' . myronEscape($fromName !== '' ? $fromName : 'Configured sender') . '<br>'
            . '<strong>Sent at:</strong> ' . myronEscape(myronNow()) . '</p>';

        if (!function_exists('myronMailTransportRegistry')) {
            $this->mailer->send($settings, $recipientEmail, $subject, $htmlBody, $textBody);
            return $recipientEmail;
        }

        $result = myronMailTransportRegistry()->activeTransport()->send(new MailEnvelope(
            to: $recipientEmail,
            subject: $subject,
            htmlBody: $htmlBody,
            textBody: $textBody,
            fromEmail: (string) ($settings['from_email'] ?? ''),
            fromName: (string) ($settings['from_name'] ?? ''),
        ));
        if (!$result->ok) {
            throw new RuntimeException($result->error ?? 'Test email failed.');
        }

        return $recipientEmail;
    }
}
