/**
 * Extracts unique email domains from a given string, ensuring each domain is prefixed with '@'.
 *
 * This method performs the following steps:
 * 1. Splits the input string by commas or pipes to extract individual domains.
 * 2. Trims whitespace from each domain and removes any empty strings.
 * 3. Removes duplicate domains.
 * 4. Ensures each domain is prefixed with '@' if it is not already.
 * 5. Joins the unique, formatted domains back into a single string separated by commas.
 *
 * @param emailDomainString - A string containing email domains separated by commas or pipes.
 * @returns A string of unique email domains, each prefixed with '@', separated by commas.
 */
function getUniqueEmailDomains(emailDomainString: string): string {
  if (
    emailDomainString === null ||
    emailDomainString === undefined ||
    emailDomainString === ''
  ) {
    return '';
  }
  const emailDomains = emailDomainString
    .split(/[,|]/) // Split by comma or pipe
    .map((domain) => domain.trim()) // Trim whitespace
    .filter((domain) => domain); // Remove empty strings

  const uniqueEmailDomains = Array.from(new Set(emailDomains)); // Remove duplicates

  /**
   * For each domain, it checks if the domain already contains an @ symbol using the includes method.
   * If the domain does not contain an @ symbol, it prepends @ to the domain.
   */
  const formattedEmailDomain = uniqueEmailDomains.map((domain) => {
    return domain.includes('@') ? domain : `@${domain}`;
  });

  // If you need the result as a string, you can join it back
  const uniqueEmailDomainString = formattedEmailDomain.join(', ');

  return uniqueEmailDomainString;
}

export { getUniqueEmailDomains };
