Source: app/util/messageParser/detectInternalUrl.js

import PageCategory from '../../data/enum/PageCategory';
import { SEGMENT_INTERNAL_LINK, SEGMENT_URL } from '../../data/enum/SegmentType';
import { INTERNAL_LINK, LAST_SLASH_OCCURRENCE_REGEX } from '../../data/regexPatterns';

const pageCategoryRegex = new RegExp(`(${Object.values(PageCategory).join('|')})(.+)`);

/**
 * Detects an user tagging in each SEGMENT_URL message segment provided to `input`. If a user tag
 * is detected, will convert it to a SEGMENT_INTERNAL_LINK and attach a internal url object.
 * @param input {Array<Object>} An array of message segments
 * @returns {Array<Object>} The processed array of message segments
 */
const detectInternalUrl = () => input =>
  input.map(segment => {
    const { type, data } = segment;

    switch (type) {
      case SEGMENT_URL: {
        if (INTERNAL_LINK.test(data.url)) {
          const parameters = data.url.split(pageCategoryRegex);
          return {
            type: SEGMENT_INTERNAL_LINK,
            data: {
              type: parameters[1],
              slug: parameters[2],
              url: data.url.replace(LAST_SLASH_OCCURRENCE_REGEX, ''),
            },
          };
        }

        return segment;
      }
      default:
        return segment;
    }
  });

export default detectInternalUrl;