from __future__ import annotations

from typing import TYPE_CHECKING

from ..objects.template import Template
from ..objects.message import Message
from ..objects.list_response import ListResponse

if TYPE_CHECKING:
    from ..connection import Connection


class Templates:
    def __init__(self, *, connection: Connection, account_id: str):
        self._connection = connection
        self._account_id = account_id

    def list(self, *, status: str | None = None, category: str | None = None) -> ListResponse[Template]:
        params = []
        if status:
            params.append(f"status={status}")
        if category:
            params.append(f"category={category}")
        path = self._base_path
        if params:
            path += "?" + "&".join(params)
        response = self._connection.get(path)
        data = [Template(t) for t in (response.get("data") or [])]
        return ListResponse(data=data, meta=response.get("meta", {}))

    def find_by_name(self, name: str) -> Template | None:
        for t in self.list().data:
            if t.name == name:
                return t
        return None

    def retrieve(self, template_id: str) -> Template:
        response = self._connection.get(f"{self._base_path}/{template_id}")
        return Template(response["data"])

    def create(self, **params) -> Template:
        response = self._connection.post(self._base_path, {"template": params})
        return Template(response["data"])

    def delete(self, template_id: str) -> bool:
        self._connection.delete(f"{self._base_path}/{template_id}")
        return True

    def sync(self) -> ListResponse[Template]:
        response = self._connection.post(f"{self._base_path}/sync")
        data = [Template(t) for t in (response.get("data") or [])]
        return ListResponse(data=data, meta=response.get("meta", {}))

    def clone(self, template_id: str) -> Template:
        response = self._connection.post(f"{self._base_path}/{template_id}/clone")
        return Template(response["data"])

    def send_test(self, template_id: str, *, to: str, variables: list | None = None) -> Message:
        body = {"to": to}
        if variables:
            body["variables"] = variables
        response = self._connection.post(f"{self._base_path}/{template_id}/send_test", body)
        return Message(response["data"])

    @property
    def _base_path(self) -> str:
        return f"/business_accounts/{self._account_id}/templates"
