import { TicketScreen } from "@point_of_sale/app/screens/ticket_screen/ticket_screen";
import { patch } from "@web/core/utils/patch";

patch(TicketScreen.prototype, {
  /**
   * Mark every refundable line of the selected order for a full refund and
   * trigger the standard refund flow.
   *
   * `onDoRefund` is what the "Refund" action of the ticket screen calls: it
   * builds the negative lines, links the combo children, carries over the
   * fiscal position and the partner, and switches to the destination order.
   */
  async onDoFullRefund() {
    const order = this.getSelectedOrder();
    if (!order) {
      return;
    }
    for (const line of order.lines) {
      const toRefundDetails = line
        .getAllLinesInCombo()
        .map((comboLine) => this.getToRefundDetail(comboLine));
      for (const toRefundDetail of toRefundDetails) {
        // Per line, and net of what was already refunded: the same
        // guard the core applies in `_onUpdateSelectedOrderline`.
        const refundableQty =
          toRefundDetail.line.qty - toRefundDetail.line.refunded_qty;
        if (refundableQty > 0) {
          toRefundDetail.qty = refundableQty;
        }
      }
    }
    await this.onDoRefund();
  },
});
