"""Resource ``customers`` — gestão de clientes.

Endpoints cobertos:

- ``POST   /customers/create``
- ``GET    /customers/list``
- ``GET    /customers/get?id=...``
- ``POST   /customers/delete``
"""

from __future__ import annotations

from collections.abc import Mapping
from typing import Any

from ..models import CreateCustomerParams, Customer
from ._base import AsyncResource, SyncResource, coerce_params, list_payload, with_id_param

CustomerInput = CreateCustomerParams | Mapping[str, Any]


class CustomersResource(SyncResource):
    """Operações síncronas sobre clientes."""

    def create(self, params: CustomerInput) -> Customer:
        """Cria (ou retorna existente) um cliente.

        Clientes são únicos por `tax_id` (CPF/CNPJ).

        Args:
            params: Dados do cliente. Aceita :class:`CreateCustomerParams` ou dict.

        Returns:
            O cliente criado/recuperado.
        """
        payload = coerce_params(params, CreateCustomerParams).to_payload()
        data = self._post("/customers/create", json=payload)
        return Customer.model_validate(data)

    def list(self) -> list[Customer]:
        """Lista todos os clientes cadastrados."""
        data = self._get("/customers/list")
        return [Customer.model_validate(item) for item in list_payload(data)]

    def get(self, id: str) -> Customer:
        """Busca um cliente pelo ID."""
        data = self._get("/customers/get", params=with_id_param(id))
        return Customer.model_validate(data)

    def delete(self, id: str) -> None:
        """Remove um cliente pelo ID."""
        self._post("/customers/delete", json={"id": id})


class AsyncCustomersResource(AsyncResource):
    """Versão assíncrona de :class:`CustomersResource`."""

    async def create(self, params: CustomerInput) -> Customer:
        payload = coerce_params(params, CreateCustomerParams).to_payload()
        data = await self._post("/customers/create", json=payload)
        return Customer.model_validate(data)

    async def list(self) -> list[Customer]:
        data = await self._get("/customers/list")
        return [Customer.model_validate(item) for item in list_payload(data)]

    async def get(self, id: str) -> Customer:
        data = await self._get("/customers/get", params=with_id_param(id))
        return Customer.model_validate(data)

    async def delete(self, id: str) -> None:
        await self._post("/customers/delete", json={"id": id})


__all__ = ["AsyncCustomersResource", "CustomersResource"]
