"""Customer CRUD operations for D365 CSU."""

from __future__ import annotations

from typing import Any

from d365_csu.client import CSUClient


def search_customers(
    client: CSUClient,
    keyword: str,
    *,
    top: int = 10,
    skip: int = 0,
) -> Any:
    """Search customers by keyword."""
    body = {
        "CustomerSearchCriteria": {
            "Keyword": keyword,
            "SearchOnlyCurrentCompany": True,
        },
        **client.build_query_result_settings(top, skip),
    }
    return client.post("Customers/Search", body)


def create_customer(client: CSUClient, payload: dict[str, Any]) -> Any:
    """Create a new customer.

    Args:
        payload: Customer entity dict (FirstName, LastName, Email, etc.).
    """
    return client.post("Customers/CreateEntity", {"entity": payload})


def update_customer(
    client: CSUClient,
    account_number: str,
    payload: dict[str, Any],
) -> Any:
    """Update an existing customer."""
    return client.post(
        f"Customers('{account_number}')/UpdateEntity",
        {"updatedEntity": payload},
    )


def get_order_history(
    client: CSUClient,
    account_number: str,
    *,
    top: int = 20,
    skip: int = 0,
) -> Any:
    """Get order history for a customer."""
    body = client.build_query_result_settings(top, skip)
    return client.post(f"Customers('{account_number}')/GetOrderHistory", body)
