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

import {Component} from "point_of_sale.Registries";
import PaymentScreen from "point_of_sale.PaymentScreen";
import {useListener} from "@web/core/utils/hooks";

const CashdroAllowManualPaymentScreen = (OriginalPaymentScreen) =>
    class extends OriginalPaymentScreen {
        setup() {
            super.setup();
            useListener("cashdro-send-manual", this._cashdroSendManual);
        }

        /**
         * Mark the Cashdro payment line as done using the amount that is already
         * set on the line (entered manually via the numpad), without contacting
         * the CashDro machine.
         *
         * Sets `cashdro_manual_done = true` on the line so the delete button
         * remains visible even in `done` state, letting the cashier undo the
         * operation in case of a mistake.
         *
         * Refuses to proceed when the amount is 0 to avoid locking the POS with
         * an undeletable zero-amount payment line.
         */
        async _cashdroSendManual({detail: line}) {
            if (!line.get_amount()) {
                this.showPopup("ErrorPopup", {
                    title: this.env._t("Importe no válido"),
                    body: this.env._t(
                        "Introduzca el importe en el teclado numérico antes de confirmar manualmente el pago."
                    ),
                });
                return;
            }
            // Flag this line as manually confirmed so the template keeps
            // showing its delete button even after the status is 'done'.
            line.cashdro_manual_done = true;
            line.set_payment_status("done");
        }
    };

Component.extend(PaymentScreen, CashdroAllowManualPaymentScreen);
