from fastapi.testclient import TestClient

from services.email_adapter_service.app import app as email_app
from services.interaction_service.app import app as interaction_app


def test_email_message_creates_interaction_and_can_be_listed():
    email_client = TestClient(email_app)
    interaction_client = TestClient(interaction_app)

    created = email_client.post(
        "/integrations/email/messages",
        json={
            "from_email": "person@example.com",
            "subject": "Portal access issue",
            "body": "Please restore access to the portal account.",
            "customer_external_id": "cust_ext_email_1",
            "queue_id": "line2",
            "priority": 2,
            "payload": {"source": "test", "mailbox": "support@example.com"},
        },
    )
    assert created.status_code == 200
    payload = created.json()
    assert payload["message_id"].startswith("eml_")
    assert payload["interaction_id"].startswith("int_")

    interaction = interaction_client.get(f"/interactions/{payload['interaction_id']}")
    assert interaction.status_code == 200
    assert interaction.json()["channel"] == "email"
    assert interaction.json()["queue_id"] == "line2"
    assert interaction.json()["customer_id"] == "cust_ext_email_1"
    assert interaction.json()["subject"] == "Portal access issue"

    timeline = interaction_client.get(f"/interactions/{payload['interaction_id']}/timeline")
    assert timeline.status_code == 200
    actions = [event["action"] for event in timeline.json()["events"]]
    assert "interaction.created" in actions
    assert "email.message_received" in actions

    listed = email_client.get("/integrations/email/messages?from_email=person@example.com")
    assert listed.status_code == 200
    assert len(listed.json()) >= 1
    assert listed.json()[-1]["from_email"] == "person@example.com"
