import toteat.toteat as toteat
from logging import getLogger

logger = getLogger(__name__)


def add_order_item(product_id: str, quantity: int, table_number: int, comment=None):
    """Agrega un item a la venta activa de la mesa en Toteat."""
    table = toteat.get_table(table_number)
    if not table:
        logger.error(f"Error: Table {table_number} not found.")
        return None

    active_sale = toteat.get_active_sale(table)
    if not active_sale:
        active_sale = toteat.create_sale(table['id'])
        if not active_sale:
            logger.error(f"Error: Could not create sale for table {table_number}.")
            return None

    item = toteat.create_item(product_id, quantity, active_sale['id'], comment)
    if not item:
        logger.error(f"Error: Could not create item for product {product_id}.")
        return None

    return item


def get_products_by_table(table_number: int):
    """Retorna los productos activos de una mesa desde Toteat."""
    return toteat.get_table_items(table_number)
