import uuid
from decimal import Decimal

import redis as redis_lib
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.api.v1.deps import get_current_user, require_role
from app.api.v1.endpoints.cart import (
    _get_or_create_cart,
    _require_whole_number_if_no_unit,
    _serialize_cart,
    add_or_merge_cart_item,
)
from app.core.config import settings
from app.db.redis import get_redis
from app.db.session import get_db
from app.models.branch import Branch
from app.models.branch_manager import BranchManager
from app.models.cart import Cart, CartItem, CartItemOption
from app.models.menu import MenuItem
from app.models.menu_option import MenuItemOption
from app.models.merchant import Merchant
from app.models.delivery import DeliveryAssignment, DeliveryAssignmentStatus
from app.models.order import (
    DeliveryMode,
    Order,
    OrderItem,
    OrderItemOption,
    OrderStatus,
    PaymentStatus,
)
from app.models.review import Review
from app.models.user import User, UserRole
from app.schemas.order import (
    CheckoutRequest,
    OrderItemOptionOut,
    OrderItemOut,
    OrderOut,
    OrderStatusUpdateRequest,
    OrderWithItemsOut,
    ReorderResponse,
    ReorderSkippedItem,
)
from app.schemas.review import ReviewCreateRequest, ReviewOut
from app.services import dispatch as dispatch_service
from app.services import grocery as grocery_service
from app.services import order_notifications
from app.services import pricing as pricing_service
from app.services import promo as promo_service
from app.services import reviews as reviews_service
from app.services.branch_hours import is_branch_open
from app.services.payments import base as payment_base
from app.services.payments import registry as payment_registry
from app.services.rate_limit import rate_limit_by_user

router = APIRouter(prefix="/orders", tags=["orders"])

_ADMIN_ROLES = {UserRole.ADMIN.value, UserRole.SUPERADMIN.value}
_NOT_FOUND = HTTPException(
    status_code=status.HTTP_404_NOT_FOUND, detail="Order not found."
)

# Which status an order can move to next, from its current status. Not
# reachable at all once CANCELLED/COMPLETED — those are terminal.
_VALID_TRANSITIONS = {
    OrderStatus.CONFIRMED.value: {
        OrderStatus.PREPARING.value,
        OrderStatus.CANCELLED.value,
    },
    OrderStatus.PREPARING.value: {
        OrderStatus.READY.value,
        OrderStatus.CANCELLED.value,
    },
    OrderStatus.READY.value: {OrderStatus.COMPLETED.value},
}


def _is_branch_staff(db: Session, branch: Branch, current_user: User) -> bool:
    """Same rule as app.api.v1.endpoints.branches._require_branch_staff:
    an admin, the merchant owner, or a manager invited to this
    specific branch."""
    if current_user.role in _ADMIN_ROLES:
        return True
    merchant = db.query(Merchant).filter(Merchant.id == branch.merchant_id).first()
    if merchant is not None and merchant.owner_id == current_user.id:
        return True
    if current_user.role == UserRole.MANAGER.value:
        return (
            db.query(BranchManager)
            .filter(
                BranchManager.branch_id == branch.id,
                BranchManager.user_id == current_user.id,
            )
            .first()
            is not None
        )
    return False


def _cancel_order(db: Session, order: Order) -> None:
    """Shared by every cancellation path — the pre-payment customer
    self-cancel (cancel_order, still PENDING_PAYMENT), the post-payment
    customer self-cancel (cancel_order, still CONFIRMED), and the
    staff-driven path (update_order_status, CONFIRMED or PREPARING).
    Everything a cancellation needs to clean up, regardless of who
    triggered it or which of those states the order was in:

    - A courier already offered/accepted this delivery gets their
      assignment cancelled and notified. One already PICKED_UP has the
      food in hand already — refused outright (409) rather than
      pretending a cancellation at that point is clean; that has to be
      resolved out of band. Never applies to a still-PENDING_PAYMENT
      order — a courier is never dispatched before payment confirms.
    - A paid (Chapa) order is flagged REFUND_PENDING rather than
      refunded automatically — see the PaymentStatus docstring for why
      this codebase doesn't call Chapa's refund API directly yet. A
      cash order's payment_status is never PAID at this point (cash is
      only collected on delivery — see courier.mark_delivered), so
      this never fires for one.
    - A redeemed promo code is un-redeemed (see
      promo_service.reverse_redemption) — redemption happens at
      checkout regardless of payment method, so this matters even for
      a PENDING_PAYMENT order that never ends up paid for.
    - The branch only hears about the cancellation (notify_branch_of_
      cancellation) if it already knew about the order in the first
      place — never for a PENDING_PAYMENT order, since
      notify_order_confirmed hasn't fired for one yet.
    """
    branch_already_notified = order.status != OrderStatus.PENDING_PAYMENT.value
    active_assignment = (
        db.query(DeliveryAssignment)
        .filter(
            DeliveryAssignment.order_id == order.id,
            DeliveryAssignment.status.in_(
                [
                    DeliveryAssignmentStatus.OFFERED.value,
                    DeliveryAssignmentStatus.ACCEPTED.value,
                    DeliveryAssignmentStatus.PICKED_UP.value,
                ]
            ),
        )
        .first()
    )
    if (
        active_assignment is not None
        and active_assignment.status == DeliveryAssignmentStatus.PICKED_UP.value
    ):
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This order has already been picked up for delivery — contact support to cancel it.",
        )

    if order.payment_status == PaymentStatus.PAID.value:
        order.payment_status = PaymentStatus.REFUND_PENDING.value

    if order.promo_code_id is not None:
        promo_service.reverse_redemption(db, order.id)

    order.status = OrderStatus.CANCELLED.value
    db.commit()
    db.refresh(order)

    if active_assignment is not None:
        active_assignment.status = DeliveryAssignmentStatus.CANCELLED.value
        db.commit()
        order_notifications.notify_delivery_cancelled(db, active_assignment)

    order_notifications.notify_order_status_changed(db, order)
    if branch_already_notified:
        order_notifications.notify_branch_of_cancellation(db, order)


def _with_items(order: Order, db: Session) -> OrderWithItemsOut:
    items = db.query(OrderItem).filter(OrderItem.order_id == order.id).all()
    item_outs = []
    for item in items:
        options = (
            db.query(OrderItemOption)
            .filter(OrderItemOption.order_item_id == item.id)
            .all()
        )
        item_outs.append(
            OrderItemOut(
                **OrderItemOut.model_validate(item).model_dump(exclude={"options"}),
                options=[OrderItemOptionOut.model_validate(o) for o in options],
            )
        )
    return OrderWithItemsOut(
        **OrderOut.model_validate(order).model_dump(),
        items=item_outs,
    )


@router.post("/checkout", response_model=OrderWithItemsOut)
def checkout(
    payload: CheckoutRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
    redis: redis_lib.Redis = Depends(get_redis),
) -> OrderWithItemsOut:
    """Turns the customer's cart into a placed order: snapshots each
    cart item's current name/price into an OrderItem (so later menu
    edits can't rewrite order history), clears the cart, and starts a
    Chapa payment. The order starts PENDING_PAYMENT — see the webhook
    in app.api.v1.endpoints.payments for how it becomes CONFIRMED."""
    rate_limit_by_user(
        redis,
        current_user.id,
        "checkout",
        settings.checkout_rate_limit_max_attempts,
        settings.checkout_rate_limit_window_seconds,
    )
    is_delivery = payload.delivery_mode == DeliveryMode.DELIVERY.value
    if is_delivery and not payload.delivery_address:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
            detail="Delivery address is required for delivery orders.",
        )
    if is_delivery and (
        payload.delivery_latitude is None or payload.delivery_longitude is None
    ):
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
            detail="Delivery location is required for delivery orders.",
        )

    cart = db.query(Cart).filter(Cart.customer_id == current_user.id).first()
    cart_items = (
        db.query(CartItem).filter(CartItem.cart_id == cart.id).all()
        if cart is not None
        else []
    )
    if cart is None or cart.branch_id is None or not cart_items:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail="Your cart is empty."
        )

    branch = db.query(Branch).filter(Branch.id == cart.branch_id).first()
    # Rechecked here, not just at add-to-cart time (app.api.v1.
    # endpoints.cart.add_item) — a cart can sit idle across the
    # boundary into closed hours, same reasoning as rechecking each
    # item's is_available below.
    if branch is not None and not is_branch_open(branch):
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This branch is currently closed.",
        )

    subtotal = Decimal("0.00")
    snapshots: list[tuple[CartItem, MenuItem, list[MenuItemOption], Decimal]] = []
    for cart_item in cart_items:
        menu_item = (
            db.query(MenuItem)
            .filter(
                MenuItem.id == cart_item.menu_item_id, MenuItem.deleted_at.is_(None)
            )
            .first()
        )
        if menu_item is None:
            raise HTTPException(
                status_code=status.HTTP_409_CONFLICT,
                detail="An item in your cart is no longer available. Update your cart and try again.",
            )
        if not menu_item.is_available:
            raise HTTPException(
                status_code=status.HTTP_409_CONFLICT,
                detail=f'"{menu_item.name}" is no longer available. Update your cart and try again.',
            )

        selected_options = [
            option
            for _cio, option in db.query(CartItemOption, MenuItemOption)
            .join(
                MenuItemOption, MenuItemOption.id == CartItemOption.menu_item_option_id
            )
            .filter(CartItemOption.cart_item_id == cart_item.id)
            .all()
        ]
        for option in selected_options:
            if not option.is_available:
                raise HTTPException(
                    status_code=status.HTTP_409_CONFLICT,
                    detail=f'"{option.name}" is no longer available. Update your cart and try again.',
                )

        options_total = sum((o.price_delta for o in selected_options), Decimal("0.00"))
        # Quantized to money precision (2dp) regardless of quantity's
        # own precision (3dp, to allow e.g. 0.5 kg) — same reasoning as
        # app.api.v1.endpoints.cart._serialize_cart.
        line_total = ((menu_item.price + options_total) * cart_item.quantity).quantize(
            Decimal("0.01")
        )
        subtotal += line_total
        snapshots.append((cart_item, menu_item, selected_options, line_total))

    if (
        branch is not None
        and branch.minimum_order_amount is not None
        and subtotal < branch.minimum_order_amount
    ):
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
            detail=(
                f"Minimum order amount for this branch is "
                f"{branch.minimum_order_amount} ETB."
            ),
        )

    promo = None
    if payload.promo_code is not None:
        try:
            promo = promo_service.validate_promo_code(
                db,
                payload.promo_code,
                branch.merchant_id if branch is not None else None,
                cart.branch_id,
                current_user.id,
                subtotal,
            )
        except promo_service.PromoCodeError as exc:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)
            ) from exc

    delivery_fee = (
        pricing_service.compute_delivery_fee(
            branch, payload.delivery_latitude, payload.delivery_longitude
        )
        if is_delivery
        else Decimal("0.00")
    )
    # service_fee is Yeneb's only revenue on an order — everything
    # else in subtotal belongs to the merchant. That split determines
    # who funds a promo code's discount: stored subtotal/service_fee
    # always stay at their full, undiscounted "list" values (an
    # accurate audit trail of what each party's normal share was);
    # discount_amount is the one place the reduction lives, and total
    # always follows the same formula below regardless of which case
    # applied.
    service_fee = pricing_service.compute_service_fee(subtotal)
    discount_amount = Decimal("0.00")
    taxable_subtotal = subtotal
    if promo is not None:
        raw_discount = pricing_service.compute_discount(promo, subtotal)
        if promo.merchant_id is not None:
            # Merchant-funded: the merchant chose to run this
            # promotion, so it comes off their own share (the food
            # price) — Yeneb's service_fee is untouched. VAT follows
            # the discounted price, since that's what's actually being
            # sold — matches the legacy system's own VAT treatment
            # (computed on the post-discount amount, never a
            # pre-discount one).
            discount_amount = raw_discount
            taxable_subtotal = subtotal - discount_amount
        else:
            # Platform-funded (no merchant_id — an admin-created,
            # Yeneb-sponsored code): comes off Yeneb's own service_fee,
            # capped there so it can never exceed what Yeneb itself
            # earns on this order. The merchant still gets their full,
            # undiscounted subtotal, and VAT (which only ever taxes
            # subtotal + delivery_fee, never service_fee) is
            # unaffected.
            discount_amount = min(raw_discount, service_fee)

    vat = pricing_service.compute_vat(taxable_subtotal + delivery_fee)
    total = subtotal + delivery_fee + service_fee + vat - discount_amount

    is_cash = payload.payment_method == "cash"
    order = Order(
        customer_id=current_user.id,
        branch_id=cart.branch_id,
        delivery_mode=payload.delivery_mode,
        delivery_address=payload.delivery_address,
        delivery_latitude=payload.delivery_latitude,
        delivery_longitude=payload.delivery_longitude,
        recipient_name=payload.recipient_name,
        recipient_phone=payload.recipient_phone,
        subtotal=subtotal,
        delivery_fee=delivery_fee,
        service_fee=service_fee,
        vat=vat,
        discount_amount=discount_amount,
        promo_code_id=promo.id if promo is not None else None,
        total=total,
        tx_ref=payment_base.generate_tx_ref(),
        # Cash has no gateway step to wait on, so the order is
        # confirmed immediately; payment_status stays PENDING until
        # the courier collects cash at delivery (see
        # app.api.v1.endpoints.courier.mark_delivered). Chapa orders
        # keep waiting at PENDING_PAYMENT until the webhook in
        # app.api.v1.endpoints.payments confirms payment.
        status=OrderStatus.CONFIRMED.value
        if is_cash
        else OrderStatus.PENDING_PAYMENT.value,
        payment_method="cash" if is_cash else None,
    )
    db.add(order)
    db.commit()
    db.refresh(order)

    if promo is not None:
        promo_service.redeem_promo_code(
            db, promo, current_user.id, order.id, discount_amount
        )

    for cart_item, menu_item, selected_options, line_total in snapshots:
        order_item = OrderItem(
            order_id=order.id,
            menu_item_id=menu_item.id,
            name_snapshot=menu_item.name,
            unit_price_snapshot=menu_item.price,
            quantity=cart_item.quantity,
            line_total=line_total,
            special_instructions=cart_item.special_instructions,
            added_by_user_id=cart_item.added_by_user_id,
        )
        db.add(order_item)
        db.commit()
        db.refresh(order_item)
        for option in selected_options:
            db.add(
                OrderItemOption(
                    order_item_id=order_item.id,
                    menu_item_option_id=option.id,
                    name_snapshot=option.name,
                    price_delta_snapshot=option.price_delta,
                )
            )
    cart_item_ids = [ci.id for ci in cart_items]
    db.query(CartItemOption).filter(
        CartItemOption.cart_item_id.in_(cart_item_ids)
    ).delete(synchronize_session=False)
    db.query(CartItem).filter(CartItem.cart_id == cart.id).delete()
    cart.branch_id = None
    db.commit()

    if not is_cash:
        name_parts = current_user.name.strip().split(" ", 1)
        first_name = name_parts[0]
        last_name = name_parts[1] if len(name_parts) > 1 else first_name
        provider = payment_registry.get_provider(payload.payment_method)
        order.chapa_checkout_url = provider.initialize_payment(
            tx_ref=order.tx_ref,
            amount=order.total,
            email=current_user.email,
            first_name=first_name,
            last_name=last_name,
            phone_number=current_user.phone.lstrip("+") if current_user.phone else None,
        )
        db.commit()
        db.refresh(order)

    # Chapa orders get dispatched later, once the webhook confirms
    # payment (see app.api.v1.endpoints.payments.chapa_webhook) — a
    # courier should never be offered an order that might still fail
    # to pay. Same reasoning for notify_order_confirmed below: a Chapa
    # order isn't CONFIRMED yet at this point (still PENDING_PAYMENT),
    # so notifying now would tell a branch about an order that might
    # never actually get paid for.
    if is_cash:
        order_notifications.notify_order_confirmed(db, order)
        if order.delivery_mode == DeliveryMode.DELIVERY.value:
            dispatch_service.dispatch_next_courier(db, redis, order)

    return _with_items(order, db)


@router.get("", response_model=list[OrderOut])
def list_orders(
    db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
) -> list[OrderOut]:
    """Customers see their own orders; suppliers/managers see orders
    for branches they own/manage; admins see everything. Anyone else
    (e.g. a courier, until delivery assignment exists) sees nothing."""
    query = db.query(Order)
    if current_user.role in _ADMIN_ROLES:
        pass
    elif current_user.role == UserRole.CUSTOMER.value:
        query = query.filter(Order.customer_id == current_user.id)
    elif current_user.role == UserRole.SUPPLIER.value:
        branch_ids = (
            db.query(Branch.id)
            .join(Merchant, Merchant.id == Branch.merchant_id)
            .filter(Merchant.owner_id == current_user.id)
        )
        query = query.filter(Order.branch_id.in_(branch_ids))
    elif current_user.role == UserRole.MANAGER.value:
        branch_ids = db.query(BranchManager.branch_id).filter(
            BranchManager.user_id == current_user.id
        )
        query = query.filter(Order.branch_id.in_(branch_ids))
    else:
        return []

    orders = query.order_by(Order.created_at.desc()).all()
    return [OrderOut.model_validate(o) for o in orders]


@router.get("/{order_id}", response_model=OrderWithItemsOut)
def get_order(
    order_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> OrderWithItemsOut:
    order = db.query(Order).filter(Order.id == order_id).first()
    if order is None:
        raise _NOT_FOUND

    branch = db.query(Branch).filter(Branch.id == order.branch_id).first()
    is_customer = order.customer_id == current_user.id
    is_staff = branch is not None and _is_branch_staff(db, branch, current_user)
    if not (is_customer or is_staff):
        raise _NOT_FOUND

    return _with_items(order, db)


@router.patch("/{order_id}/status", response_model=OrderOut)
def update_order_status(
    order_id: uuid.UUID,
    payload: OrderStatusUpdateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> OrderOut:
    order = db.query(Order).filter(Order.id == order_id).first()
    if order is None:
        raise _NOT_FOUND

    branch = db.query(Branch).filter(Branch.id == order.branch_id).first()
    if branch is None or not _is_branch_staff(db, branch, current_user):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="You don't manage this branch.",
        )

    if order.status == OrderStatus.PENDING_PAYMENT.value:
        # Cash orders never sit in PENDING_PAYMENT (see checkout) — this
        # only ever fires for a Chapa order still waiting on the webhook.
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This order hasn't been paid for yet.",
        )

    if (
        payload.status == OrderStatus.COMPLETED.value
        and order.delivery_mode == DeliveryMode.DELIVERY.value
    ):
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="Delivery orders are completed by the courier, not this endpoint.",
        )

    allowed_next = _VALID_TRANSITIONS.get(order.status, set())
    if payload.status not in allowed_next:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail=f"Can't move an order from {order.status} to {payload.status}.",
        )

    if payload.status == OrderStatus.CANCELLED.value:
        _cancel_order(db, order)
        return OrderOut.model_validate(order)

    order.status = payload.status
    db.commit()
    db.refresh(order)
    order_notifications.notify_order_status_changed(db, order)
    return OrderOut.model_validate(order)


_SELF_CANCELLABLE = {OrderStatus.PENDING_PAYMENT.value, OrderStatus.CONFIRMED.value}


@router.post("/{order_id}/cancel", response_model=OrderOut)
def cancel_order(
    order_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> OrderOut:
    """A customer can self-cancel while PENDING_PAYMENT (a Chapa order
    that never finished paying) or CONFIRMED (paid, but the branch
    hasn't started preparing it yet). Once PREPARING, the kitchen has
    already started — only staff can cancel from there (via
    update_order_status), same _cancel_order cleanup either way."""
    order = (
        db.query(Order)
        .filter(Order.id == order_id, Order.customer_id == current_user.id)
        .first()
    )
    if order is None:
        raise _NOT_FOUND
    if order.status not in _SELF_CANCELLABLE:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This order can no longer be self-cancelled — contact the merchant.",
        )

    _cancel_order(db, order)
    return OrderOut.model_validate(order)


@router.post("/{order_id}/mark-refunded", response_model=OrderOut)
def mark_order_refunded(
    order_id: uuid.UUID,
    db: Session = Depends(get_db),
    _admin: User = Depends(require_role(UserRole.ADMIN, UserRole.SUPERADMIN)),
) -> OrderOut:
    """Confirms a REFUND_PENDING order's refund was actually completed
    out of band (bank transfer, Chapa dashboard, etc — see the
    PaymentStatus docstring). Admin-only: this is a finance action, not
    something branch staff or the customer self-report."""
    order = db.query(Order).filter(Order.id == order_id).first()
    if order is None:
        raise _NOT_FOUND
    if order.payment_status != PaymentStatus.REFUND_PENDING.value:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This order doesn't have a refund pending.",
        )

    order.payment_status = PaymentStatus.REFUNDED.value
    db.commit()
    db.refresh(order)
    return OrderOut.model_validate(order)


@router.post("/{order_id}/reorder", response_model=ReorderResponse)
def reorder_order(
    order_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> ReorderResponse:
    """Re-adds every line from a past order (any status — even a
    cancelled one) to the customer's current cart, merging into
    whatever's already there rather than replacing it. Anything that's
    changed since — the item removed/marked unavailable, an option
    that no longer exists, a quantity that's no longer valid for the
    item — is silently dropped and reported back in `skipped`, not
    a wholesale failure; the customer still gets everything that's
    still orderable, same as the item-level skip already used when
    checkout finds a stale line."""
    order = (
        db.query(Order)
        .filter(Order.id == order_id, Order.customer_id == current_user.id)
        .first()
    )
    if order is None:
        raise _NOT_FOUND

    branch = db.query(Branch).filter(Branch.id == order.branch_id).first()
    if branch is None:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This branch no longer exists.",
        )
    if not is_branch_open(branch):
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This branch is currently closed.",
        )

    cart = _get_or_create_cart(db, current_user.id)
    if cart.branch_id is not None and cart.branch_id != order.branch_id:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail=(
                "Your cart has items from a different merchant. "
                "Clear it first to reorder from here."
            ),
        )

    order_items = db.query(OrderItem).filter(OrderItem.order_id == order.id).all()
    skipped: list[ReorderSkippedItem] = []
    added_count = 0
    for order_item in order_items:
        menu_item = (
            db.query(MenuItem)
            .filter(
                MenuItem.id == order_item.menu_item_id, MenuItem.deleted_at.is_(None)
            )
            .first()
        )
        if menu_item is None or not menu_item.is_available:
            skipped.append(
                ReorderSkippedItem(
                    name=order_item.name_snapshot, reason="No longer available"
                )
            )
            continue

        grocery_details = grocery_service.get_grocery_details(db, menu_item.id)
        try:
            _require_whole_number_if_no_unit(grocery_details, order_item.quantity)
        except HTTPException:
            skipped.append(
                ReorderSkippedItem(
                    name=order_item.name_snapshot,
                    reason="No longer available in the original quantity",
                )
            )
            continue

        historical_option_ids = [
            o.menu_item_option_id
            for o in db.query(OrderItemOption)
            .filter(OrderItemOption.order_item_id == order_item.id)
            .all()
            if o.menu_item_option_id is not None
        ]
        selected_options = (
            db.query(MenuItemOption)
            .filter(
                MenuItemOption.id.in_(historical_option_ids),
                MenuItemOption.deleted_at.is_(None),
                MenuItemOption.is_available.is_(True),
            )
            .all()
            if historical_option_ids
            else []
        )

        if cart.branch_id is None:
            cart.branch_id = menu_item.branch_id
            db.commit()

        add_or_merge_cart_item(
            db,
            cart,
            menu_item,
            order_item.quantity,
            selected_options,
            order_item.special_instructions,
            current_user.id,
        )
        added_count += 1

    if added_count == 0 and order_items:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="None of the items in this order are still available.",
        )

    return ReorderResponse(
        cart=_serialize_cart(db, cart), added_count=added_count, skipped=skipped
    )


@router.post("/{order_id}/review", response_model=ReviewOut)
def create_review(
    order_id: uuid.UUID,
    payload: ReviewCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> ReviewOut:
    """One review per order (see the Review model docstring), and only
    once it's actually COMPLETED — reviewing an order that was never
    fulfilled (still in progress, or cancelled) isn't meaningful
    feedback about the branch."""
    order = (
        db.query(Order)
        .filter(Order.id == order_id, Order.customer_id == current_user.id)
        .first()
    )
    if order is None:
        raise _NOT_FOUND
    if order.status != OrderStatus.COMPLETED.value:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="Only a completed order can be reviewed.",
        )
    if db.query(Review).filter(Review.order_id == order.id).first() is not None:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This order has already been reviewed.",
        )

    review = Review(
        order_id=order.id,
        customer_id=current_user.id,
        branch_id=order.branch_id,
        rating=payload.rating,
        comment=payload.comment,
    )
    db.add(review)
    db.commit()
    db.refresh(review)
    return reviews_service.to_review_out(review, current_user.name)
