import smtplib

from app.core.config import settings
from app.services import email as email_service


class _FakeSMTP:
    """Stands in for smtplib.SMTP_SSL — a real connection is exactly
    what these tests must never attempt."""

    instances: list["_FakeSMTP"] = []

    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.login_calls: list[tuple[str, str]] = []
        self.sent_messages: list = []
        _FakeSMTP.instances.append(self)

    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        return False

    def login(self, username, password):
        self.login_calls.append((username, password))

    def send_message(self, message):
        self.sent_messages.append(message)


def test_send_email_does_nothing_without_smtp_password(monkeypatch):
    monkeypatch.setattr(settings, "smtp_password", "")

    def _fail(*args, **kwargs):
        raise AssertionError("should not attempt a real SMTP connection")

    monkeypatch.setattr(smtplib, "SMTP_SSL", _fail)
    email_service.send_email("a@example.com", "Subject", "Body")  # no raise


def test_send_email_connects_and_sends_when_configured(monkeypatch):
    _FakeSMTP.instances.clear()
    monkeypatch.setattr(settings, "smtp_host", "mail.yeneb.com")
    monkeypatch.setattr(settings, "smtp_port", 465)
    monkeypatch.setattr(settings, "smtp_username", "noreply@yeneb.com")
    monkeypatch.setattr(settings, "smtp_password", "secret")
    monkeypatch.setattr(settings, "smtp_sender_name", "Yeneb Delivery")
    monkeypatch.setattr(smtplib, "SMTP_SSL", _FakeSMTP)

    email_service.send_email("a@example.com", "Your code", "Your code is 123456.")

    assert len(_FakeSMTP.instances) == 1
    fake = _FakeSMTP.instances[0]
    assert fake.host == "mail.yeneb.com"
    assert fake.port == 465
    assert fake.login_calls == [("noreply@yeneb.com", "secret")]
    assert len(fake.sent_messages) == 1
    sent = fake.sent_messages[0]
    assert sent["To"] == "a@example.com"
    assert sent["Subject"] == "Your code"
    assert sent["From"] == "Yeneb Delivery <noreply@yeneb.com>"
    assert sent.get_content().strip() == "Your code is 123456."


def test_send_email_with_html_builds_multipart_alternative(monkeypatch):
    _FakeSMTP.instances.clear()
    monkeypatch.setattr(settings, "smtp_host", "mail.yeneb.com")
    monkeypatch.setattr(settings, "smtp_port", 465)
    monkeypatch.setattr(settings, "smtp_username", "noreply@yeneb.com")
    monkeypatch.setattr(settings, "smtp_password", "secret")
    monkeypatch.setattr(settings, "smtp_sender_name", "YENEB CODS")
    monkeypatch.setattr(smtplib, "SMTP_SSL", _FakeSMTP)

    email_service.send_email(
        "a@example.com",
        "Your code",
        "Your code is 123456.",
        html="<html><body>Your code is <b>123456</b>.</body></html>",
    )

    sent = _FakeSMTP.instances[0].sent_messages[0]
    assert sent["From"] == "YENEB CODS <noreply@yeneb.com>"
    assert sent.is_multipart()
    parts = {part.get_content_type(): part for part in sent.walk()}
    assert "text/plain" in parts
    assert "text/html" in parts
    assert parts["text/plain"].get_content().strip() == "Your code is 123456."
    assert "<b>123456</b>" in parts["text/html"].get_content()


def test_send_templated_email_renders_and_sends_both_parts(monkeypatch):
    _FakeSMTP.instances.clear()
    monkeypatch.setattr(settings, "smtp_host", "mail.yeneb.com")
    monkeypatch.setattr(settings, "smtp_port", 465)
    monkeypatch.setattr(settings, "smtp_username", "noreply@yeneb.com")
    monkeypatch.setattr(settings, "smtp_password", "secret")
    monkeypatch.setattr(smtplib, "SMTP_SSL", _FakeSMTP)

    email_service.send_templated_email(
        "a@example.com",
        "Verify your email — YENEB CODS",
        "otp",
        {
            "heading": "Verify your email",
            "intro_text": "Enter this code to finish creating your YENEB account.",
            "code": "482913",
            "expiry_minutes": 5,
            "name": "Abebe",
        },
    )

    sent = _FakeSMTP.instances[0].sent_messages[0]
    parts = {part.get_content_type(): part for part in sent.walk()}
    assert "482913" in parts["text/plain"].get_content()
    assert "482913" in parts["text/html"].get_content()
