/** @odoo-module */
/**
 * Override cashdro_send_payment_request to apply POS currency/cash rounding
 * before sending amount to CashDro, keeping OCA integration flow.
 */

// Import the whole module and take PaymentCashdro from its exports
// Use asset alias path and import PaymentCashdro directly
import { PaymentCashdro } from "@pos_payment_method_cashdro/js/payment_cashdro.esm";

PaymentCashdro.prototype.cashdro_send_payment_request = async function (order) {
    const payment_line = order.selected_paymentline;
    try {
        // If pos_cashdro_refund is installed this method handles payouts.
        // Rounding is not applicable to refunds so we delegate and return.
        const due = order.get_due(payment_line);
        if (due < 0) {
            if (this._cashdro_send_refund_request) {
                return this._cashdro_send_refund_request(order);
            }
            // Refund module not installed – nothing we can do.
            payment_line.set_payment_status("retry");
            return false;
        }
        // Cashdro treats decimals as positions in an integer we also have
        // to deal with floating point computing to avoid decimals at the
        // end or the drawer will reject our request.
        const amount = Math.round((order.get_due(payment_line) + order.get_rounding_applied()) * 100);
        console.log("amount: " + amount);
        const res = await this._cashdro_request(
            this._cashdro_payment_url({amount: amount})
        );
        // It comes handy to log the response from the drawer, as
        // we can diagnose the right sytmoms for each issue
        console.log(res);
        const operation_id = res.data || "";
        this.pos.get_order().cashdro_operation = operation_id;
        // Acknowledge the operation
        var ack_url = this._cashdro_ack_url(operation_id);
        const res_ack = await this._cashdro_request(ack_url);
        // Validate the operation
        console.log(res_ack);
        var ask_url = this._cashdro_ask_url(operation_id);
        const operation_data = await this._cashdro_request_payment(ask_url);
        // This might be too verbose, but it helps a lot to diagnose issues and
        // their reasons.
        console.log(operation_data);
        var data = JSON.parse(operation_data.data);
        payment_line.cashdro_operation_data = data;
        var tendered = data.operation.totalin / 100;
        payment_line.set_amount(tendered);
    } catch (error) {
        // We wan't to be able to retry after any error.
        // TODO: catch specific exceptions
        payment_line.set_payment_status("retry");
        throw error;
    }
    return true;
};
