from sqlalchemy import update, func

from shared.models.market import CartItem
from shared.models.order import Order


async def clear_cart_for_order(session, order: Order, *, page_post_id: int | None = None) -> None:
    """
    Soft-delete CartItem rows belonging to this order's user_id/session_id.

    When *page_post_id* is given, only items whose market_place belongs to
    that page are cleared.  Otherwise all items are cleared (legacy behaviour).
    """
    filters = [CartItem.deleted_at.is_(None)]
    if order.user_id is not None:
        filters.append(CartItem.user_id == order.user_id)
    if order.session_id is not None:
        filters.append(CartItem.session_id == order.session_id)

    if len(filters) == 1:
        # no user_id/session_id on order – nothing to clear
        return

    if page_post_id is not None:
        filters.append(CartItem.market_place_container_id == page_post_id)

    await session.execute(
        update(CartItem)
        .where(*filters)
        .values(deleted_at=func.now())
    )
