"""send_email() has exactly one delivery path: Mailchimp Transactional
(Mandrill). A tenant with no active connection gets a clear error, never a
silent send from a shared address.

Every dependency send_email() reaches out to (branding, tenant settings,
image generation, and the Mailchimp connection lookup) is mocked, so these
tests never touch a real database or network call.
"""
from unittest.mock import MagicMock

from app.core.email_branding import Branding
from app.services.messaging import email as email_module

BRAND = Branding(name="Acme", reply_to="support@acme.example")
COPY = {"header": "hi", "footer": "bye", "aiDisclaimer": ""}

MAILCHIMP_CONNECTION = {
    "transactional_api_key": "md-abc123",
    "from_email": "shivraj@galaxiq.ai",
    "from_name": "GalaxiQ AI",
}


def _patched(monkeypatch, mailchimp_connection):
    monkeypatch.setattr(email_module, "get_email_settings",
                        lambda tenant_id: {**COPY, "enabled": True})
    monkeypatch.setattr(email_module, "brand_for_tenant", lambda tenant_id=None: BRAND)
    monkeypatch.setattr(email_module, "image_generation_available", lambda: False)
    monkeypatch.setattr(email_module, "_mailchimp_connection_for",
                        lambda tenant_id: mailchimp_connection)


def test_a_connected_tenant_sends_through_mandrill(monkeypatch):
    _patched(monkeypatch, MAILCHIMP_CONNECTION)
    send_via_mandrill = MagicMock(return_value={
        "status": "sent", "to": "user@example.com", "subject": "Hi"})
    monkeypatch.setattr(email_module, "send_via_mandrill", send_via_mandrill)

    result = email_module.send_email(
        "user@example.com", "Hi", "body", tenant_id="org_test")

    assert result["status"] == "sent"
    send_via_mandrill.assert_called_once()
    assert send_via_mandrill.call_args[0][0] == MAILCHIMP_CONNECTION
    assert send_via_mandrill.call_args[0][1] == "user@example.com"
    assert send_via_mandrill.call_args.kwargs["reply_to"] == "support@acme.example"


def test_a_mandrill_send_failure_is_returned_as_is(monkeypatch):
    _patched(monkeypatch, MAILCHIMP_CONNECTION)
    failure = {"status": "error", "detail": "Could not send the email."}
    monkeypatch.setattr(email_module, "send_via_mandrill", MagicMock(return_value=failure))

    result = email_module.send_email(
        "user@example.com", "Hi", "body", tenant_id="org_test")

    assert result == failure


def test_a_tenant_with_no_mailchimp_connection_gets_a_clear_error(monkeypatch):
    _patched(monkeypatch, None)
    send_via_mandrill = MagicMock()
    monkeypatch.setattr(email_module, "send_via_mandrill", send_via_mandrill)

    result = email_module.send_email(
        "user@example.com", "Hi", "body", tenant_id="org_test")

    assert result == {"status": "error", "detail": "Connect Mailchimp to send emails."}
    send_via_mandrill.assert_not_called()


def test_a_call_with_no_tenant_id_still_short_circuits_cleanly(monkeypatch):
    # A caller with no tenant context (none exist today, but the signature
    # allows it) must not crash trying to look up a connection for None --
    # it just gets the same "not configured" error as any other tenant
    # without a connection.
    monkeypatch.setattr(email_module, "brand_for_tenant", lambda tenant_id=None: BRAND)
    monkeypatch.setattr(email_module, "image_generation_available", lambda: False)
    mailchimp_connection_for = MagicMock(return_value=None)
    monkeypatch.setattr(email_module, "_mailchimp_connection_for", mailchimp_connection_for)

    result = email_module.send_email("user@example.com", "Hi", "body")

    assert result["status"] == "error"
    mailchimp_connection_for.assert_called_once_with(None)


# --- _mailchimp_connection_for -------------------------------------------------

def test_an_active_connection_is_returned(monkeypatch):
    monkeypatch.setattr(email_module, "get_mailchimp_connection",
                        lambda tenant_id: MAILCHIMP_CONNECTION)
    assert email_module._mailchimp_connection_for("org_test") == MAILCHIMP_CONNECTION


def test_none_tenant_id_short_circuits_before_any_lookup(monkeypatch):
    get_mailchimp_connection = MagicMock()
    monkeypatch.setattr(email_module, "get_mailchimp_connection", get_mailchimp_connection)
    assert email_module._mailchimp_connection_for(None) is None
    get_mailchimp_connection.assert_not_called()


# --- email_configured ---------------------------------------------------------

def test_email_configured_is_true_for_a_connected_tenant(monkeypatch):
    monkeypatch.setattr(email_module, "_mailchimp_connection_for",
                        lambda tenant_id: MAILCHIMP_CONNECTION)
    assert email_module.email_configured("org_test") is True


def test_email_configured_is_false_with_no_connection(monkeypatch):
    monkeypatch.setattr(email_module, "_mailchimp_connection_for", lambda tenant_id: None)
    assert email_module.email_configured("org_test") is False
