const UserError = require('vn-loopback/util/user-error');

module.exports = Self => {
    Self.remoteMethodCtx('end', {
        description: 'Ends electronic payment transaction',
        accessType: 'WRITE',
        accepts: [
            {
                arg: 'orderId',
                type: 'string',
                required: true,
            }, {
                arg: 'status',
                type: 'string',
                required: true,
            }
        ],
        http: {
            path: `/end`,
            verb: 'POST'
        }
    });

    Self.end = async(ctx, orderId, status) => {
        const userId = ctx.req.accessToken.userId;
        const transaction = await Self.findById(orderId, {
            fields: ['id', 'clientFk']
        });

        if (transaction?.clientFk != userId)
            throw new UserError('Transaction not owned by user');

        await Self.rawSql(
            'CALL hedera.tpvTransaction_end(?, ?)', [
                orderId,
                status
            ], {userId});
    };
};