import { ParsedDialogContent } from './dialog.model';

/**
 * Regular expression to match URLs in text.
 * Matches http:// and https:// URLs.
 */
const URL_REGEX = /https?:\/\/[^\s]+/i;

/**
 * Parses the dialog content and extracts the first URL.
 * Splits the content into text before the URL, the URL itself, and text after.
 *
 * @param content - The dialog content string to parse
 * @returns ParsedDialogContent with the split content
 */
export const parseDialogContentForUrl = (
  content: string | undefined,
): ParsedDialogContent => {
  if (!content) {
    return { textBefore: '', url: null, textAfter: '' };
  }

  const match = content.match(URL_REGEX);

  if (!match || match.index === undefined) {
    return { textBefore: content, url: null, textAfter: '' };
  }

  const url = match[0];
  const urlIndex = match.index;
  const textBefore = content.substring(0, urlIndex).trim();
  const textAfter = content.substring(urlIndex + url.length).trim();

  return { textBefore, url, textAfter };
};

/**
 * Checks if the given content contains a URL.
 *
 * @param content - The content string to check
 * @returns true if a URL is found, false otherwise
 */
export const contentHasUrl = (content: string | undefined): boolean => {
  if (!content) {
    return false;
  }
  return URL_REGEX.test(content);
};
