import * as bcrypt from 'bcrypt';
import { createHmac, timingSafeEqual } from 'crypto';

export const hashValue = async (value: string, saltRounds: number): Promise<string> =>
  bcrypt.hash(value, saltRounds);

export const compareHash = async (value: string, hashedValue: string): Promise<boolean> =>
  bcrypt.compare(value, hashedValue);

export const hashHighEntropyValue = (value: string, secret: string): string =>
  `sha256:${createHmac('sha256', secret).update(value).digest('hex')}`;

export const compareStoredHighEntropyValue = async (
  value: string,
  storedValue: string,
  secret: string,
): Promise<boolean> => {
  if (storedValue.startsWith('sha256:')) {
    const nextValue = hashHighEntropyValue(value, secret);
    return timingSafeEqual(Buffer.from(nextValue), Buffer.from(storedValue));
  }

  return compareHash(value, storedValue);
};
