import { uuidv4 } from '@firebase/util';
import crypto from 'crypto';


function createRandomString(length: number) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}


export function getCurrentTimeStamp() {
  return new Date().getTime();
}


export function createDocumentKey() {
  const uniqueString = createRandomString(6)
  const timeStamp = getCurrentTimeStamp().toString();

  // Half of the timestamp will go in front, and the other half will go at the end
  const halfLength = timeStamp.length / 2;
  const front = timeStamp.substring(0, halfLength);
  const back = timeStamp.substring(halfLength, timeStamp.length);

  return `${front}-${uniqueString}-${back}`;
}


export function createApiKey() {
  const timeStamp = getCurrentTimeStamp().toString();
  const uniqueString = uuidv4();

  // Hash ssh256 the timestand and keep only 8 characters
  const hash = crypto.createHash('sha256').update(timeStamp).digest('hex').substring(0, 8);

  // Hash ssh256 the combination of the unique string and the timestamp
  const hash2 = crypto.createHash('sha256').update(`${uniqueString}`).digest('hex')

  return `${hash}-${hash2}`;
}