from __future__ import annotations

from urllib.parse import quote
from typing import TYPE_CHECKING

from ..objects.business_account import BusinessAccount
from ..objects.connect_request import ConnectRequest
from ..objects.list_response import ListResponse

if TYPE_CHECKING:
    from ..client import WhatsrbCloud
    from ..connection import Connection


class BusinessAccounts:
    def __init__(self, *, client: WhatsrbCloud, connection: Connection):
        self._client = client
        self._connection = connection

    def list(self) -> ListResponse[BusinessAccount]:
        response = self._connection.get("/business_accounts")
        data = [BusinessAccount(a, client=self._client) for a in (response.get("data") or [])]
        return ListResponse(data=data, meta=response.get("meta", {}))

    def retrieve(self, id: str) -> BusinessAccount:
        response = self._connection.get(f"/business_accounts/{id}")
        return BusinessAccount(response["data"], client=self._client)

    def connect(self) -> ConnectRequest:
        response = self._connection.post("/business_accounts/connect")
        return ConnectRequest(response["data"], client=self._client)

    def connect_manual(self, **params) -> BusinessAccount:
        response = self._connection.post("/business_accounts", {"business_account": params})
        return BusinessAccount(response["data"], client=self._client)

    def create(self, **params) -> BusinessAccount:
        return self.connect_manual(**params)

    def window(self, id: str, *, phone_number: str) -> dict:
        response = self._connection.get(f"/business_accounts/{id}/window?phone_number={quote(phone_number)}")
        return response["data"]

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