"""Cart management operations for D365 CSU."""

from __future__ import annotations

from typing import Any

from d365_csu.client import CSUClient


def create_empty_cart(client: CSUClient) -> Any:
    """Create an empty cart."""
    return client.post("Carts/CreateEmptyCart", {})


def get_cart(client: CSUClient, cart_id: str) -> Any:
    """Get a cart by ID."""
    return client.get(f"Carts('{cart_id}')")


def add_cart_lines(
    client: CSUClient,
    cart_id: str,
    lines: list[dict[str, Any]],
) -> Any:
    """Add line items to a cart.

    Args:
        lines: List of dicts with ProductId, Quantity, UnitOfMeasureSymbol.
    """
    return client.post(f"Carts('{cart_id}')/AddCartLines", {"cartLines": lines})


def remove_cart_lines(
    client: CSUClient,
    cart_id: str,
    line_ids: list[str],
) -> Any:
    """Remove line items from a cart."""
    return client.post(f"Carts('{cart_id}')/RemoveCartLines", {"lineIds": line_ids})


def checkout(
    client: CSUClient,
    cart_id: str,
    *,
    receipt_email: str = "",
    cart_tender_lines: list[dict[str, Any]] | None = None,
) -> Any:
    """Checkout a cart to create a sales order."""
    body: dict[str, Any] = {
        "receiptEmail": receipt_email,
        "tokenizedPaymentCard": None,
        "receiptNumberSequence": None,
        "cartTenderLines": cart_tender_lines or [],
    }
    return client.post(f"Carts('{cart_id}')/Checkout", body)
