from typing import Dict, Any, List, Optional
from ..http_client import HTTPClient
import base64


class IoTMessagingResource:
    def __init__(self, http: HTTPClient):
        self._http = http

    def send(self, device_id: str, payload: bytes, port: int = 1) -> Dict[str, Any]:
        return self._http.post("/iot/messages", json={
            "deviceId": device_id,
            "payload": base64.b64encode(payload).decode(),
            "port": port,
            "direction": "mobile-terminated",
        })

    def send_batch(self, messages: List[Dict[str, Any]]) -> Dict[str, Any]:
        encoded = []
        for msg in messages:
            m = dict(msg)
            if isinstance(m.get("payload"), bytes):
                m["payload"] = base64.b64encode(m["payload"]).decode()
            encoded.append(m)
        return self._http.post("/iot/messages/batch", json={"messages": encoded})

    def list(self, device_id: str = None, page: int = 1, page_size: int = 20) -> Dict[str, Any]:
        params = {"page": page, "pageSize": page_size}
        if device_id:
            params["deviceId"] = device_id
        return self._http.get("/iot/messages", params=params)

    def get(self, message_id: str) -> Dict[str, Any]:
        return self._http.get(f"/iot/messages/{message_id}")
