from fastapi.testclient import TestClient

from services.interaction_service.app import app as interaction_app
from services.webchat_adapter_service.app import app as webchat_app


def test_webchat_message_creates_interaction_and_can_be_listed():
    webchat_client = TestClient(webchat_app)
    interaction_client = TestClient(interaction_app)

    created = webchat_client.post(
        "/integrations/webchat/messages",
        json={
            "session_id": "web_session_1",
            "text": "Need help with the checkout page",
            "visitor_name": "Visitor One",
            "customer_external_id": "cust_ext_1",
            "queue_id": "line2",
            "priority": 2,
            "payload": {"source": "test", "subject": "Checkout issue"},
        },
    )
    assert created.status_code == 200
    payload = created.json()
    assert payload["message_id"].startswith("wcm_")
    assert payload["interaction_id"].startswith("int_")

    interaction = interaction_client.get(f"/interactions/{payload['interaction_id']}")
    assert interaction.status_code == 200
    assert interaction.json()["channel"] == "webchat"
    assert interaction.json()["queue_id"] == "line2"
    assert interaction.json()["customer_id"] == "cust_ext_1"

    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 "webchat.message_received" in actions

    listed = webchat_client.get("/integrations/webchat/messages?session_id=web_session_1")
    assert listed.status_code == 200
    assert len(listed.json()) >= 1
    assert listed.json()[-1]["session_id"] == "web_session_1"
