const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
const mergeFilters = require('vn-loopback/util/filter').mergeFilters;

module.exports = Self => {
    Self.remoteMethod('byWarehouse', {
        description: 'Returns a list of agencies from a warehouse',
        accepts: [{
            arg: 'filter',
            type: 'Object',
            description: `Filter defining where, order, offset, and limit - must be a JSON-encoded string`
        }],
        returns: {
            type: ['object'],
            root: true
        },
        http: {
            path: `/byWarehouse`,
            verb: 'GET'
        }
    });

    Self.byWarehouse = async filter => {
        const conn = Self.dataSource.connector;
        const where = {isActive: true};
        filter = mergeFilters(filter, {where});

        let stmt = new ParameterizedSQL(
            `SELECT id, name, warehouseFk
                FROM (
                    SELECT DISTINCT am.id, am.name, am.isActive, zw.warehouseFk
                        FROM zoneWarehouse zw
                            JOIN zone z ON z.id = zw.zoneFk
                            JOIN agencyMode am ON am.id = z.agencyModeFk) am`);
        stmt.merge(conn.makeSuffix(filter));

        return conn.executeStmt(stmt);
    };
};