"""Message resource methods."""

from typing import Optional


class MessagesResource:
    """Message send, reply, list, and search methods."""

    def __init__(self, client):
        self._client = client

    def list(self, inbox_id: str, **params):
        """List messages in an inbox."""

        return self._client.request("GET", f"/inboxes/{inbox_id}/messages", params=params)

    def get(self, inbox_id: str, message_id: str):
        """Get a single message."""

        return self._client.request("GET", f"/inboxes/{inbox_id}/messages/{message_id}")["data"]

    def wait_for(
        self,
        inbox_id: str,
        *,
        direction: str = "inbound",
        from_address: Optional[str] = None,
        subject_contains: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        poll_interval_ms: Optional[int] = None,
        after: Optional[str] = None,
    ):
        """Wait for a matching message. Useful for CI/CD and flow testing."""

        params = {
            "direction": direction,
            "from_address": from_address,
            "subject_contains": subject_contains,
            "timeout_ms": timeout_ms,
            "poll_interval_ms": poll_interval_ms,
            "after": after,
        }
        filtered_params = {key: value for key, value in params.items() if value is not None}
        return self._client.request("GET", f"/inboxes/{inbox_id}/messages/wait", params=filtered_params)

    def send(self, inbox_id: str, **payload):
        """Send an outbound message."""

        if "bodyText" in payload:
            payload["body_text"] = payload.pop("bodyText")
        if "bodyHtml" in payload:
            payload["body_html"] = payload.pop("bodyHtml")
        return self._client.request("POST", f"/inboxes/{inbox_id}/messages", json=payload)["data"]

    def reply(self, inbox_id: str, message_id: str, **payload):
        """Reply to an existing message."""

        if "bodyText" in payload:
            payload["body_text"] = payload.pop("bodyText")
        if "bodyHtml" in payload:
            payload["body_html"] = payload.pop("bodyHtml")
        return self._client.request("POST", f"/inboxes/{inbox_id}/messages/{message_id}/reply", json=payload)["data"]

    def search(self, inbox_id: str, query: str, limit: int = 20):
        """Search messages by text query."""

        return self._client.request("POST", f"/inboxes/{inbox_id}/messages/search", json={"query": query, "limit": limit})

    def update_labels(self, inbox_id: str, message_id: str, labels):
        """Replace labels on a message."""

        return self._client.request("PUT", f"/inboxes/{inbox_id}/messages/{message_id}/labels", json={"labels": labels})["data"]
