from __future__ import annotations

from datetime import datetime


class Message:
    def __init__(self, data: dict):
        self.id = data.get("id")
        self.session_id = data.get("session_id")
        self.business_account_id = data.get("business_account_id")
        self.to = data.get("to")
        self.status = data.get("status")
        self.message_type = data.get("message_type")
        self.content = data.get("content")
        self.direction = data.get("direction")
        self.whatsapp_message_id = data.get("whatsapp_message_id")
        self.wamid = data.get("wamid")
        self.error_message = data.get("error_message")
        self.template_name = data.get("template_name")
        self.template_language = data.get("template_language")
        self.sent_at = _parse_time(data.get("sent_at"))
        self.delivered_at = _parse_time(data.get("delivered_at"))
        self.read_at = _parse_time(data.get("read_at"))
        self.created_at = _parse_time(data.get("created_at"))

    @property
    def is_queued(self) -> bool:
        return self.status == "queued"

    @property
    def is_sent(self) -> bool:
        return self.status == "sent"

    @property
    def is_delivered(self) -> bool:
        return self.status == "delivered"

    @property
    def is_read(self) -> bool:
        return self.status == "read"

    @property
    def is_failed(self) -> bool:
        return self.status == "failed"

    def to_dict(self) -> dict:
        return {
            "id": self.id,
            "session_id": self.session_id,
            "to": self.to,
            "status": self.status,
            "message_type": self.message_type,
            "content": self.content,
        }


def _parse_time(value: str | None) -> datetime | None:
    if value is None:
        return None
    try:
        return datetime.fromisoformat(value)
    except (ValueError, TypeError):
        return None
