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

module.exports = Self => {
    Self.remoteMethodCtx('getShipped', {
        description: 'Returns the first shipped possible for params',
        accessType: 'READ',
        accepts: [{
            arg: 'landed',
            type: 'date',
            required: true
        },
        {
            arg: 'addressFk',
            type: 'number',
            required: true
        },
        {
            arg: 'agencyModeFk',
            type: 'number',
            required: true
        },
        {
            arg: 'warehouseFk',
            type: 'number',
            required: true
        }],
        returns: {
            type: 'date',
            root: true
        },
        http: {
            path: `/getShipped`,
            verb: 'get'
        }
    });

    Self.getShipped = async(ctx, landed, addressFk, agencyModeFk, warehouseFk, options) => {
        const myOptions = {};

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

        const stmts = [];
        const userId = ctx.req.accessToken.userId;
        const models = Self.app.models;
        const isProductionAssistant = await models.VnUser.hasRole(userId, 'productionAssi', myOptions);
        stmts.push(new ParameterizedSQL(
            `CALL vn.zone_getShipped(?, ?, ?, ?)`, [
                landed,
                addressFk,
                agencyModeFk,
                isProductionAssistant
            ]
        ));

        const rsIndex = stmts.push(new ParameterizedSQL(
            `SELECT * FROM tmp.zoneGetShipped WHERE warehouseFk = ?`, [
                warehouseFk
            ]
        )) - 1;

        const sql = ParameterizedSQL.join(stmts, ';');
        const shipped = await Self.rawStmt(sql, myOptions);

        return shipped[rsIndex][0];
    };
};