module.exports = Self => {
    Self.remoteMethodCtx('editableStates', {
        description: 'Gets the editable states according the user role ',
        accessType: 'READ',
        accepts: {
            arg: 'filter',
            type: 'object'
        },
        returns: {
            type: ['Object'],
            root: true
        },
        http: {
            path: `/editableStates`,
            verb: 'GET'
        }
    });

    Self.editableStates = async(ctx, filter) => {
        let userId = ctx.req.accessToken.userId;
        let models = Self.app.models;
        let statesList = await models.State.find({where: filter.where});

        let isProduction = await models.Account.hasRole(userId, 'production');
        let isSalesPerson = await models.Account.hasRole(userId, 'salesPerson');
        let isAdministrative = await models.Account.hasRole(userId, 'administrative');

        if (isProduction || isAdministrative)
            return statesList;

        if (isSalesPerson) {
            return statesList = statesList.filter(stateList =>
                stateList.alertLevel === 0 || stateList.code === 'PICKER_DESIGNED'
            );
        }

        return statesList.filter(stateList => stateList.alertLevel === 0);
    };
};