"""Business logic layer for order operations.

Applies business rules (e.g., quantity caps) and delegates to the
repository for persistence. Errors from the repository are caught
and wrapped to provide a clean interface for the handler layer.
"""

from src import repository
from src.models import AppError


def create_order(data):
    """Create a new order with business rules applied.

    Applies a quantity cap of 1000 before saving.

    Args:
        data: Order data dict.

    Returns:
        The created order dict.

    Raises:
        AppError: If the order cannot be created.
    """
    if data.get("quantity", 0) > 1000:
        data = dict(data)
        data["quantity"] = 1000

    try:
        order = repository.save_order(data)
    except Exception as e:
        raise AppError(str(e))

    return order


def get_order(order_id):
    """Retrieve an existing order.

    Args:
        order_id: The order identifier.

    Returns:
        The order dict.

    Raises:
        AppError: If the order cannot be retrieved.
    """
    try:
        return repository.get_order(order_id)
    except Exception as e:
        raise AppError(str(e))
