"""Data access layer for orders.

Handles storage, retrieval, and input validation at the persistence
boundary. Validation failures should raise appropriate application
errors so upstream layers can handle them correctly.
"""

from src.models import NotFoundError

_orders = {}
_next_id = 1


def get_order(order_id):
    """Retrieve an order by ID.

    Args:
        order_id: The order identifier.

    Returns:
        Order dict if found.

    Raises:
        NotFoundError: If the order doesn't exist.
    """
    if order_id not in _orders:
        raise NotFoundError(f"Order {order_id} not found", code="ORDER_NOT_FOUND")
    return _orders[order_id]


def save_order(data):
    """Validate and persist a new order.

    Args:
        data: Order data dict with customer, quantity, price fields.

    Returns:
        The created order dict with id and computed total.

    Raises:
        ValueError: If required fields are missing or invalid.
    """
    global _next_id

    if not data.get("customer"):
        raise ValueError("customer is required")

    quantity = data.get("quantity", 0)
    if not isinstance(quantity, int) or quantity < 1:
        raise ValueError("quantity must be a positive integer")

    price = data.get("price", 0)
    if not isinstance(price, (int, float)) or price <= 0:
        raise ValueError("price must be positive")

    order = {
        "id": _next_id,
        "customer": data["customer"],
        "quantity": quantity,
        "price": price,
        "total": quantity * price,
    }
    _orders[_next_id] = order
    _next_id += 1
    return order
