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

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

    Self.getLanded = async(ctx, shipped, addressFk, agencyModeFk, warehouseFk, options) => {
        const models = Self.app.models;
        const myOptions = {};

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

        const canSeeExpired = await models.ACL.checkAccessAcl(ctx, 'Agency', 'seeExpired', 'READ');

        const stmts = [];
        stmts.push(new ParameterizedSQL(
            'CALL vn.zone_getLanded(?, ?, ?, ?, ?)', [
                shipped,
                addressFk,
                agencyModeFk,
                warehouseFk,
                canSeeExpired
            ]
        ));

        const rsIndex = stmts.push('SELECT * FROM tmp.zoneGetLanded') - 1;

        stmts.push('DROP TEMPORARY TABLE tmp.zoneGetLanded');

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

        return landed[rsIndex][0];
    };
};