import pytest
import os
from unittest.mock import patch, MagicMock
from app.email_sender import EmailSender


@pytest.fixture
def sender():
    return EmailSender()


def test_send_debug_mode(sender):
    with patch("os.name", "nt"):
        result = sender.send("test@test.com", "Test", "Body", "from@test.com")
        assert result is True

    log_path = os.path.join(os.path.dirname(__file__), "..", "logs", "emails.log")
    if os.path.isfile(log_path):
        with open(log_path, "r", encoding="utf-8") as f:
            content = f.read()
        assert "test@test.com" in content
        assert "Test" in content
        os.remove(log_path)


def test_send_linux_mode(sender):
    mock_proc = MagicMock()
    mock_proc.returncode = 0

    with patch("os.name", "posix"), \
         patch("subprocess.run", return_value=mock_proc):
        result = sender.send("test@test.com", "Test", "Body", "from@test.com")
        assert result is True


def test_send_with_default_from(sender):
    with patch("app.email_sender.config_reader") as mock_config:
        mock_config.get_mail_from.return_value = "no-reply@aegisone.ru"
        result = sender.send("test@test.com", "Test", "Body")
        assert result is True


def test_send_ticket_escalation(sender):
    with patch.object(sender, "send", return_value=True) as mock_send:
        result = sender.send_ticket_escalation(
            to="support@aegisone.ru",
            subject="Test",
            user_info="ID: 123",
            contact="+79990000000",
            inquiry="Need help",
            history="Client: Hello",
        )
        assert result is True
        mock_send.assert_called_once()
        args = mock_send.call_args[0]
        assert "ID: 123" in args[2]
        assert "Need help" in args[2]
