'use strict';

var bcrypt = require('bcrypt');
var utilDocumentId = require('../../shared/utils/UtilDocumentId');

const hash = async (pass) => {
    const saltRounds = config.get("saltRounds") || 10;
    const salt = await bcrypt.genSalt(saltRounds);
    return bcrypt.hash(pass, salt);
};

/* encryption & validation methods */
//Create hash for plain password
exports.createHash = function (pass, callback) {
    if (!pass) {
        callback();
        return;
    }
    
    hash(pass).then(hash => {
        callback(hash);
    });
};

// Validate plain password vs hash password
exports.validatePassword = function (plainPass, hashedPass, callback) {
    bcrypt.compare(plainPass, hashedPass, function (err, res) {
        if (err) {
            callback(err, null);
        } else {
            if (res) {
                callback(null, res);
            } else {
                callback('passwords do not match', null);
            }
        }
    });
};


/* encryption & validation methods */
//Create hash for password  reset token
exports.createResetTokenHash = function (callback) {
    var resetToken = utilDocumentId.generateId();
    hash(resetToken).then(hash => {
        callback(hash);
    });
};
