module.exports = Self => {
    Self.remoteMethod('getAlternative', {
        description: 'Returns a list of items and possible alternative locations',
        accessType: 'READ',
        accepts: [{
            arg: 'shelvingCode',
            type: 'string',
            required: true,
        }],
        returns: {
            type: ['object'],
            root: true
        },
        http: {
            path: `/getAlternative`,
            verb: 'GET'
        }
    });

    Self.getAlternative = async(shelvingCode, options) => {
        const models = Self.app.models;
        const myOptions = {};

        if (typeof options == 'object')
            Object.assign(myOptions, options);

        const shelving = await models.Shelving.findOne({
            where: {
                code: shelvingCode
            }
        });

        if (!shelving) return [];
        const {id: shelvingFk} = shelving;
        const filterItemShelvings = {
            fields: ['id', 'visible', 'itemFk', 'shelvingFk'],
            where: {shelvingFk},
            include: [
                {
                    relation: 'item',
                    scope: {
                        fields: ['longName', 'name', 'size']
                    }
                },

            ]
        };

        let itemShelvings = await models.ItemShelving.find(filterItemShelvings, myOptions);

        if (itemShelvings) {
            const [alternatives] = await models.ItemShelving.rawSql('CALL vn.itemShelving_getAlternatives(?)',
                [shelvingCode], myOptions
            );
            return itemShelvings.map(itemShelving => {
                const item = itemShelving.item();

                const shelvings = alternatives.filter(alternative => alternative.itemFk == itemShelving.itemFk);

                return {
                    id: itemShelving.id,
                    itemFk: itemShelving.itemFk,
                    name: item.name,
                    size: item.size,
                    longName: item.longName,
                    quantity: itemShelving.visible,
                    shelvings
                };
            });
        }
    };
};