const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;

module.exports = Self => {
    Self.remoteMethod('listPackaging', {
        description: 'Returns all packages including item',
        accessType: 'READ',
        accepts: [{
            arg: 'filter',
            type: 'Object',
            required: false,
            description: 'Filter defining where and paginated data',
            http: {source: 'query'}
        }],
        returns: {
            type: ['Object'],
            root: true
        },
        http: {
            path: `/listPackaging`,
            verb: 'get'
        }
    });

    Self.listPackaging = async filter => {
        let conn = Self.dataSource.connector;
        let stmt = new ParameterizedSQL(
            `SELECT name, itemFk, packagingFk
                FROM (SELECT i.name, i.id itemFk, p.id packagingFk
                        FROM item i 
                            JOIN packaging p ON i.id = p.itemFk
                        WHERE i.name <> '' AND p.isPackageReturnable) p`
        );

        stmt.merge(conn.makeSuffix(filter));
        return conn.executeStmt(stmt);
    };
};