/* Copyright Criptomart
   License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

   Apply the PoS cash rounding to the amount requested to the CashDro, keeping
   the OCA integration flow untouched.
*/

import { PaymentCashdro } from "@pos_payment_method_cashdro/js/payment_cashdro.esm";
import { patch } from "@web/core/utils/patch";

patch(PaymentCashdro.prototype, {
    /**
     * @override
     * The base module asks the CashDro for the plain due amount, which ignores
     * the cash rounding configured in the PoS. As the drawer can only give back
     * change with the coins it holds, we request the amount the customer is
     * really expected to pay: the due amount with the cash rounding applied,
     * which is the very same amount core defaults a payment line to.
     *
     * Only the url builder is patched so the rest of the payment flow of the
     * base module (request, acknowledge, polling and error handling) is kept.
     */
    _cashdro_payment_url(parameters) {
        const order = this.pos.get_order();
        const line = order.get_selected_paymentline();
        if (!line || !order.shouldRound(line.payment_method_id)) {
            return super._cashdro_payment_url(...arguments);
        }
        // CashDro treats decimals as positions in an integer, so we round the
        // product to avoid the trailing decimals of the floating point
        // computation or the drawer would reject our request.
        const amount = Math.round(
            order.getDefaultAmountDueToPayIn(line.payment_method_id) * 100
        );
        return super._cashdro_payment_url({ ...parameters, amount });
    },
});
