import CryptoJS from 'crypto-js';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
const {JWT_SECRET, KONG_CONSUMER_KEY, KONG_CONSUMER_SECRET, KONG_EXPIRED_MINUTES} =
  process.env;

export const getSecret = () => process.env.JWT_SECRET;
// CryptoJS
//  const generatePassword = (username: string, password: string) => {
//   const salt = CryptoJS.SHA256(username).toString();
//   const crypt = CryptoJS.PBKDF2(password, salt, {
//     keySize: 256 / 32,
//   }).toString();
//   return {password: crypt, salt: salt};
// };

// export const generatePassword = (username, password) => {
//   // Gunakan salt acak (16 bytes diubah ke string hex)
//   const salt = CryptoJS.lib.WordArray.random(16).toString(CryptoJS.enc.Hex);

//   // Gunakan PBKDF2 dengan iterasi yang lebih tinggi dan keySize lebih besar
//   const crypt = CryptoJS.PBKDF2(password, salt, {
//     keySize: 512 / 32, // 64 bytes
//     iterations: 25000, // Minimal 100k iterasi untuk keamanan yang lebih baik
//   }).toString();

//   return {password: crypt, salt: salt};
// };

// export const verifyPassword = (
//   inputPassword: string,
//   storedHash: string,
//   username: string,
// ) => {
//   const salt = CryptoJS.SHA256(username).toString();
//   const inputHash = CryptoJS.PBKDF2(inputPassword, salt, {
//     keySize: 256 / 32,
//   }).toString();

//   return inputHash === storedHash;
// };
// End CryptoJS

// Bcrypt
export const generatePassword = async (password) => {
  const salt = await bcrypt.genSalt(10); // 10 rounds = balance speed & security
  const hash = await bcrypt.hash(password, salt);
  return {password: hash, salt: salt};
};

export const verifyPassword = async (
  inputPassword: string,
  storedHash: string,
) => {
  return await bcrypt.compare(inputPassword, storedHash);
};
// End Bcrypt

export const generateToken = (user: any): string => {
  return jwt.sign(
    {
      sub: user,
      iss: JWT_SECRET,
      iat: Math.floor(Date.now() / 1000),
      exp: Math.floor(Date.now() / 1000) + 1800, // 30 menit
    },
    JWT_SECRET,
  );
};
