import crypto from "crypto";
import bcrypt from "bcrypt";

//function to hash the password using bcrypt or crypto
export const hashPassword = async (
  password: string,
  secureKey: string,
  algorithm: "crypto" | "bcrypt"
) => {
  if (algorithm === "bcrypt") {
    const salt = bcrypt.genSaltSync(10);
    return await bcrypt.hash(password + secureKey, salt);
  } else if (algorithm === "crypto") {
    const hash = crypto.createHash("sha512");
    hash.update(password + secureKey);
    return hash.digest("hex");
  } else {
    throw new Error(
      "The algorithm you entered is not supported, do use of bcrypt or crypto in your program."
    );
  }
};

// function to compare the hashed password with the provided password
export const verifyPassword = async (
  password: string,
  secureKey: string,
  hashPassword: string,
  algorithm: "crypto" | "bcrypt"
) => {
  if (algorithm === "bcrypt") {
    return await bcrypt.compare(password + secureKey, hashPassword);
  } else if (algorithm === "crypto") {
    const hash = crypto.createHash("sha512");
    hash.update(password + secureKey);
    return hash.digest("hex") === hashPassword;
  } else {
    throw new Error(
      "The algorithm you entered is not supported, do use of bcrypt or crypto in your program."
    );
  }
};
