from __future__ import annotations

import re
from typing import TYPE_CHECKING

from ..errors import ValidationError
from ..objects.message import Message
from ..objects.list_response import ListResponse

if TYPE_CHECKING:
    from ..connection import Connection

VALID_TYPES = ("text", "image", "video", "audio", "document", "location", "contact")
PHONE_PATTERN = re.compile(r"^\+\d{1,15}$")


class Messages:
    def __init__(self, *, connection: Connection, session_id: str):
        self._connection = connection
        self._session_id = session_id

    def list(self) -> ListResponse[Message]:
        response = self._connection.get(f"/sessions/{self._session_id}/messages")
        data = [Message(m) for m in (response.get("data") or [])]
        return ListResponse(data=data, meta=response.get("meta", {}))

    def retrieve(self, message_id: str) -> Message:
        response = self._connection.get(f"/sessions/{self._session_id}/messages/{message_id}")
        return Message(response["data"])

    def create(self, *, to: str, text: str | None = None, message_type: str | None = None, content: str | None = None) -> Message:
        _validate_phone(to)
        if text:
            body = {"to": to, "message_type": "text", "content": text}
        else:
            _validate_type(message_type or ("text" if content else None))
            body = {"to": to, "message_type": message_type, "content": content}
        response = self._connection.post(f"/sessions/{self._session_id}/messages", {"message": body})
        return Message(response["data"])


def _validate_phone(to: str) -> None:
    if not to:
        raise ValidationError("Phone number is required")
    if not PHONE_PATTERN.match(to):
        raise ValidationError("Invalid phone number format")


def _validate_type(msg_type: str | None) -> None:
    if msg_type and msg_type not in VALID_TYPES:
        raise ValidationError(f"Invalid message type: {msg_type}")
