// @ts-check

const { createHmac } = require("crypto");

/**
 * # Hash password Function
 * @param {object} param0
 * @param {string} param0.password - Password to hash
 * @param {string} [param0.encryptionKey] - Encryption key
 * @returns {string}
 */
module.exports = function hashPassword({ password, encryptionKey }) {
    const finalEncryptionKey =
        encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;

    if (!finalEncryptionKey?.match(/.{8,}/)) {
        throw new Error("Encryption key is invalid");
    }

    const hmac = createHmac("sha512", finalEncryptionKey);
    hmac.update(password);
    let hashed = hmac.digest("base64");
    return hashed;
};
