"""Unit tests for EmailService SMTP routing."""

from unittest.mock import AsyncMock, patch

import pytest

from app.config import settings
from app.services.email_service import EmailService


@pytest.mark.asyncio
async def test_send_email_logs_dev_otp_when_smtp_placeholder_and_mailpit_unavailable(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """Placeholder SMTP must not fake success without OTP visibility in debug."""
    monkeypatch.setattr(settings, "APP_DEBUG", True)
    monkeypatch.setattr(settings, "APP_ENV", "development")
    monkeypatch.setattr(settings, "SMTP_USER", "noreply@yourdomain.com")
    monkeypatch.setattr(settings, "SMTP_PASSWORD", "your-app-password")

    service = EmailService()
    with patch.object(service, "_dispatch", new_callable=AsyncMock) as mock_dispatch:
        mock_dispatch.side_effect = ConnectionRefusedError("mailpit down")
        success, error = await service.send_email(
            "staff@example.com",
            "Test",
            "<p>hi</p>",
            dev_otp="123456",
        )

    assert success is True
    assert error is None


def test_password_reset_template_renders_otp_and_branding() -> None:
    service = EmailService()
    html = service.render_template(
        "password_reset_otp.html",
        {"user_name": "Admin", "otp": "704296"},
    )
    assert "704296" in html
    assert "Admin" in html
    assert "Password reset verification" in html
    assert "Verification code" in html


def test_effective_smtp_from_uses_authenticated_user(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(settings, "SMTP_USER", "real@gmail.com")
    monkeypatch.setattr(settings, "SMTP_FROM", "noreply@munallab.com")
    assert settings.effective_smtp_from == "real@gmail.com"
