import pytest
from app.services.email import send_contact_email
from unittest.mock import patch, MagicMock, AsyncMock

@pytest.mark.asyncio
async def test_send_contact_email_success(mocker):
    # Create a mock SMTP instance that works as async context manager
    mock_smtp = MagicMock()
    mock_smtp.__aenter__ = AsyncMock(return_value=mock_smtp)
    mock_smtp.__aexit__ = AsyncMock(return_value=None)
    mock_smtp.login = AsyncMock()
    mock_smtp.send_message = AsyncMock()

    # Patch aiosmtplib.SMTP to return our mock instance
    with patch("aiosmtplib.SMTP", return_value=mock_smtp):
        await send_contact_email(
            name="Test",
            email="test@example.com",
            subject="Test Subject",
            message="Hello World"
        )
        # Verify login and send_message were called
        mock_smtp.login.assert_called_once()
        mock_smtp.send_message.assert_called_once()

@pytest.mark.asyncio
async def test_send_contact_email_handles_error(mocker):
    # Simulate SMTP constructor raising an exception
    with patch("aiosmtplib.SMTP", side_effect=Exception("SMTP connection failed")):
        # Function should catch exception and not raise
        await send_contact_email("Test", "test@example.com", "Test", "Hello")
        # If no exception raised, test passes
