"""Customers resource."""

from typing import Any, AsyncIterator, Dict, Iterator, Optional

from ..client import AsyncHttpClient, HttpClient
from ..pagination import PaginatedResponse, async_paginate, paginate
from ..types import CustomerDto

BASE_PATH = "/api/v1/customers"


class CustomersResource:
    """Synchronous customers resource.

    Wraps endpoints under ``/api/v1/customers``.
    """

    def __init__(self, client: HttpClient) -> None:
        self._client = client

    def create(
        self,
        *,
        email: Optional[str] = None,
        first_name: Optional[str] = None,
        last_name: Optional[str] = None,
        phone: Optional[str] = None,
        telegram_id: Optional[str] = None,
    ) -> CustomerDto:
        """Create a new customer.

        Args:
            email: Customer email address. Optional.
            first_name: Customer first name. Optional.
            last_name: Customer last name. Optional.
            phone: Customer phone number (E.164 format). Optional.
            telegram_id: Customer Telegram user ID. Optional.

        Returns:
            The created customer object.
        """
        body: Dict[str, Any] = {}
        if email is not None:
            body["email"] = email
        if first_name is not None:
            body["firstName"] = first_name
        if last_name is not None:
            body["lastName"] = last_name
        if phone is not None:
            body["phone"] = phone
        if telegram_id is not None:
            body["telegramId"] = telegram_id

        return self._client.request("POST", BASE_PATH, json_body=body)

    def list(
        self,
        *,
        page: int = 1,
        size: int = 10,
        search: Optional[str] = None,
    ) -> PaginatedResponse:
        """List customers with pagination.

        Returns:
            A PaginatedResponse containing CustomerDto items.
        """
        params: Dict[str, Any] = {
            "page": page,
            "size": size,
            "search": search,
        }
        return self._client.request_paginated("GET", BASE_PATH, params=params)

    def list_auto_paginate(self, **kwargs: Any) -> Iterator[CustomerDto]:
        """Iterate over all customers across all pages."""
        return paginate(self.list, params=kwargs)

    def get(self, customer_id: str) -> CustomerDto:
        """Get a customer by ID.

        Args:
            customer_id: The customer UUID.

        Returns:
            The customer object.
        """
        return self._client.request("GET", f"{BASE_PATH}/{customer_id}")


class AsyncCustomersResource:
    """Asynchronous customers resource."""

    def __init__(self, client: AsyncHttpClient) -> None:
        self._client = client

    async def create(
        self,
        *,
        email: Optional[str] = None,
        first_name: Optional[str] = None,
        last_name: Optional[str] = None,
        phone: Optional[str] = None,
        telegram_id: Optional[str] = None,
    ) -> CustomerDto:
        """Create a new customer (async)."""
        body: Dict[str, Any] = {}
        if email is not None:
            body["email"] = email
        if first_name is not None:
            body["firstName"] = first_name
        if last_name is not None:
            body["lastName"] = last_name
        if phone is not None:
            body["phone"] = phone
        if telegram_id is not None:
            body["telegramId"] = telegram_id

        return await self._client.request("POST", BASE_PATH, json_body=body)

    async def list(
        self,
        *,
        page: int = 1,
        size: int = 10,
        search: Optional[str] = None,
    ) -> PaginatedResponse:
        """List customers with pagination (async)."""
        params: Dict[str, Any] = {
            "page": page,
            "size": size,
            "search": search,
        }
        return await self._client.request_paginated("GET", BASE_PATH, params=params)

    def list_auto_paginate(self, **kwargs: Any) -> AsyncIterator[CustomerDto]:
        """Iterate over all customers across all pages (async)."""
        return async_paginate(self.list, params=kwargs)

    async def get(self, customer_id: str) -> CustomerDto:
        """Get a customer by ID (async)."""
        return await self._client.request("GET", f"{BASE_PATH}/{customer_id}")
