import { parse, ParsedDomain } from 'psl';

function isParsedDomain(result): result is ParsedDomain {
  return (result as ParsedDomain).domain !== undefined;
}

export default function extractDomain(urlString: string): string {
  try {
    if (
      typeof urlString === 'string' &&
      !urlString.startsWith('http://') &&
      !urlString.startsWith('https://')
    ) {
      urlString = 'http://' + urlString;
    }
    const parsedUrl = new URL(urlString);
    if ('hostname' in parsedUrl) {
      const parsedDomain = parse(parsedUrl.hostname);
      if (isParsedDomain(parsedDomain)) {
        return parsedDomain.domain;
      }
    }
    return urlString;
  } catch (error) {
    console.error('Error in extractDomain', error);
    return urlString;
  }
}
