import { TEMP_EMAIL_DOMAIN } from "./constants";
import { isAliasAvailable } from "./db";
import crypto from 'crypto';
import * as random_words from "random-words";

export async function generateAliasEmail(label: string, style: 'words' | 'random', labelAtEnd: boolean): Promise<string> {
  let email: string;
  do {
    let randomString: string;
    switch (style) {
      case 'words':
        randomString = random_words.generate(2).join('');
        break;
      case 'random':
        randomString = crypto
          .randomBytes(8)
          .toString('base64')
          .replace(/\W/, ''); // Delete special characters
        break;
      default:
        throw new Error("Invalid style");
    }
    email = `${labelAtEnd ? `${randomString}-${label}` : `${label}-${randomString}`}@${TEMP_EMAIL_DOMAIN}`;
  } while (!await isAliasAvailable(email, true));

  return email;
}