import type { Parent, Root } from 'mdast';
import { visit } from 'unist-util-visit';

const ALLOWED_DATA_IMAGE_MIME_PATTERN = /^data:image\/(?:webp|gif|jpe?g|png)(?:;|$)/i;

function isBlockedMarkdownUrl(url: string): boolean {
  const trimmed = url.trim();

  if (/^(?:javascript|vbscript):/i.test(trimmed)) {
    return true;
  }

  if (/^data:/i.test(trimmed)) {
    return !ALLOWED_DATA_IMAGE_MIME_PATTERN.test(trimmed);
  }

  return false;
}

export function remarkStripDangerousContent(): () => (tree: Root) => void {
  return () => (tree: Root) => {
    const htmlNodes: { parent: Parent; index: number }[] = [];

    visit(tree, 'html', (_node, index, parent) => {
      if (parent && typeof index === 'number') {
        htmlNodes.push({ parent, index });
      }
    });

    for (const entry of htmlNodes.sort((left, right) => right.index - left.index)) {
      entry.parent.children.splice(entry.index, 1);
    }

    visit(tree, 'link', (node) => {
      if (typeof node.url === 'string' && isBlockedMarkdownUrl(node.url)) {
        node.url = '';
      }
    });

    visit(tree, 'image', (node) => {
      if (typeof node.url === 'string' && isBlockedMarkdownUrl(node.url)) {
        node.url = '';
      }
    });
  };
}
