from unittest.mock import MagicMock, patch

from app.core.email import SmtpMailer, get_mailer, memory_mailer, send_template_email


def test_memory_mailer_latest_token():
    memory_mailer.clear()
    send_template_email(
        to="user@example.com",
        template="verify_email",
        subject="Verify",
        body="Open link\nTOKEN:abc123\n",
    )
    assert memory_mailer.latest_token("user@example.com", "verify_email") == "abc123"


def test_smtp_mailer_sends_message(monkeypatch):
    monkeypatch.setattr("app.core.email.settings.email_delivery_mode", "smtp")
    monkeypatch.setattr("app.core.email.settings.smtp_from", "noreply@example.com")
    monkeypatch.setattr("app.core.email.settings.smtp_host", "localhost")
    monkeypatch.setattr("app.core.email.settings.smtp_port", 1025)
    monkeypatch.setattr("app.core.email.settings.smtp_user", "")
    monkeypatch.setattr("app.core.email.settings.smtp_password", "")

    smtp_instance = MagicMock()
    with patch("app.core.email.smtplib.SMTP") as smtp_cls:
        smtp_cls.return_value.__enter__.return_value = smtp_instance
        get_mailer().send("user@example.com", "Subject", "Body", "verify_email")
        smtp_instance.send_message.assert_called_once()
