
module.exports = Self => {
    Self.remoteMethod('checkoutInfo', {
        description: 'Get the checkout information for an order',
        accessType: 'READ',
        accepts: [
            {
                arg: 'id',
                type: 'Number',
                description: 'The order id'
            }
        ],
        returns: {
            type: 'Object',
            description: 'The checkout information',
            root: true,
        },
        http: {
            path: `/:id/checkoutInfo`,
            verb: 'GET'
        }
    });

    Self.checkoutInfo = async id => {
        let $ = Self.app.models;

        let order = await Self.findById(id, {
            fields: ['taxableBase', 'tax', 'total', 'clientFk']
        });

        let {credit} = await $.Client.findById(order.clientFk, {
            fields: ['credit']
        });

        let [{debt}] = await queryP(
            `SELECT vn.clientGetDebt(?, CURDATE()) debt`,
            [order.clientFk]
        );

        let bank = await $.MainAccountBank.findOne();

        return {order, credit, debt, bank};
    };

    Self.remoteMethod('confirm', {
        description: 'Confirms an order',
        accessType: 'WRITE',
        accepts: [
            {
                arg: 'id',
                type: 'Number',
                description: 'The order id'
            }
        ],
        returns: {
            type: 'Boolean',
            description: 'The confirm result',
            root: true,
        },
        http: {
            path: `/:id/confirm`,
            verb: 'POST'
        }
    });

    Self.confirm = async id => {
        await queryP(`CALL hedera.order_confirm(?)`, [id]);
        return true;
    };

    async function queryP(sql, params) {
        return new Promise((resolve, reject) => {
            Self.dataSource.connector.query(sql, params, (err, res) => {
                if (err) return reject(err);
                return resolve(res);
            })
        });
    }
};
