module.exports = Self => {
    Self.remoteMethod('recoverPassword', {
        description: 'Send email to the user',
        accepts: [
            {
                arg: 'user',
                type: 'string',
                description: 'The user name or email',
                required: true
            }
        ],
        http: {
            path: `/recoverPassword`,
            verb: 'POST'
        }
    });

    Self.recoverPassword = async function(user) {
        const models = Self.app.models;

        const usesEmail = user.indexOf('@') !== -1;
        if (!usesEmail) {
            const account = await models.Account.findOne({
                fields: ['email'],
                where: {name: user}
            });
            user = account.email;
        }

        try {
            await models.user.resetPassword({email: user, emailTemplate: 'recover-password'});
        } catch (err) {
            if (err.code === 'EMAIL_NOT_FOUND')
                return;
            else
                throw err;
        }
    };
};