"""AgentBill Customers 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("customers")


class CustomersResource(WithRawResponseMixin):
    """
    Customers resource for CRUD operations.

    All HTTP calls go through the shared ``AgentBillHTTPClient`` for consistent
    auth, retries, timeouts, and error mapping.

    Example:
        >>> from agentbill import AgentBill
        >>> ab = AgentBill.init({"api_key": "agb_..."})
        >>> customers = ab.customers.list(limit=10)
        >>> customer = ab.customers.create(name="Acme Corp", email="billing@acme.com")
    """

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

    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,
        limit: int = 50,
        offset: int = 0,
        search: Optional[str] = None,
    ) -> Dict[str, Any]:
        """List customers with pagination and search."""
        params = {"limit": str(limit), "offset": str(offset)}
        if search:
            params["search"] = search

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

    def create(
        self,
        name: str,
        email: str,
        phone: Optional[str] = None,
        website: Optional[str] = None,
        external_id: Optional[str] = None,
        metadata: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Create a new customer."""
        payload: Dict[str, Any] = {"name": name, "email": email}
        if phone:
            payload["phone"] = phone
        if website:
            payload["website"] = website
        if external_id:
            payload["external_id"] = external_id
        if metadata:
            payload["metadata"] = metadata

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

    def get(self, customer_id: str, by_external_id: bool = False) -> Dict[str, Any]:
        """Get a customer by ID or external_id."""
        params = {}
        if by_external_id:
            params["external_id"] = customer_id
        else:
            params["id"] = customer_id

        resp = self._http.get(self._resource_path, params=params)
        result = resp.data
        if "data" in result and isinstance(result["data"], list):
            if len(result["data"]) == 0:
                raise Exception("Customer not found")
            return result["data"][0]
        return result

    def update(
        self,
        customer_id: str,
        name: Optional[str] = None,
        email: Optional[str] = None,
        phone: Optional[str] = None,
        website: Optional[str] = None,
        metadata: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Update a customer."""
        payload: Dict[str, Any] = {"id": customer_id}
        if name:
            payload["name"] = name
        if email:
            payload["email"] = email
        if phone:
            payload["phone"] = phone
        if website:
            payload["website"] = website
        if metadata:
            payload["metadata"] = metadata

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

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