"""AgentBill Contacts Resource - CRUD operations via unified HTTP client"""

from typing import Any, Dict, Optional
from ..http_client import AgentBillHTTPClient
from ..raw_response import WithRawResponseMixin
from ..logger import get_logger

_log = get_logger("contacts")


class ContactsResource(WithRawResponseMixin):
    """Contacts resource for CRUD operations via unified HTTP client."""

    _resource_path = "/functions/v1/api-contacts"

    def __init__(self, config: Dict[str, Any], http_client: "AgentBillHTTPClient" = None):
        self.config = config
        self.debug = config.get("debug", False)
        self._http = http_client

    def list(
        self,
        account_id: Optional[str] = None,
        limit: int = 50,
        offset: int = 0,
        search: Optional[str] = None,
    ) -> Dict[str, Any]:
        """List contacts with pagination and filtering."""
        params = {"limit": str(limit), "offset": str(offset)}
        if search:
            params["search"] = search
        if account_id:
            params["account_id"] = account_id

        resp = self._http.get(self._resource_path, params=params)
        return resp.data

    def create(
        self,
        account_id: str,
        name: str,
        email: str,
        phone: Optional[str] = None,
        billing_address_line1: Optional[str] = None,
        billing_address_line2: Optional[str] = None,
        billing_city: Optional[str] = None,
        billing_state: Optional[str] = None,
        billing_postal_code: Optional[str] = None,
        billing_country: Optional[str] = None,
        metadata: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Create a new contact."""
        payload: Dict[str, Any] = {"account_id": account_id, "name": name, "email": email}
        for key, val in {
            "phone": phone, "billing_address_line1": billing_address_line1,
            "billing_address_line2": billing_address_line2, "billing_city": billing_city,
            "billing_state": billing_state, "billing_postal_code": billing_postal_code,
            "billing_country": billing_country, "metadata": metadata,
        }.items():
            if val:
                payload[key] = val

        _log.debug("Creating contact: %s", name)
        resp = self._http.post(self._resource_path, json=payload)
        return resp.data

    def get(self, contact_id: str) -> Dict[str, Any]:
        """Get a contact by ID."""
        resp = self._http.get(self._resource_path, params={"id": contact_id})
        return resp.data

    def update(
        self,
        contact_id: str,
        name: Optional[str] = None,
        email: Optional[str] = None,
        phone: Optional[str] = None,
        billing_address_line1: Optional[str] = None,
        billing_address_line2: Optional[str] = None,
        billing_city: Optional[str] = None,
        billing_state: Optional[str] = None,
        billing_postal_code: Optional[str] = None,
        billing_country: Optional[str] = None,
        metadata: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Update a contact."""
        payload: Dict[str, Any] = {"id": contact_id}
        for key, val in {
            "name": name, "email": email, "phone": phone,
            "billing_address_line1": billing_address_line1,
            "billing_address_line2": billing_address_line2,
            "billing_city": billing_city, "billing_state": billing_state,
            "billing_postal_code": billing_postal_code, "billing_country": billing_country,
            "metadata": metadata,
        }.items():
            if val is not None:
                payload[key] = val

        resp = self._http.patch(self._resource_path, json=payload)
        return resp.data

    def delete(self, contact_id: str) -> None:
        """Delete a contact."""
        self._http.request("DELETE", self._resource_path, json={"id": contact_id})
