import StarterKit from '@tiptap/starter-kit';
import Link from '@tiptap/extension-link';

/** Match the server's supported comment links for typed, pasted and autolinked text. */
export function isReviewLinkAllowed(value: string): boolean {
  if (/[\u0000-\u0020\u007f]/.test(value)) return false;
  try {
    const url = new URL(value);
    return (url.protocol === 'https:' || url.protocol === 'http:') ? Boolean(url.hostname) : url.protocol === 'mailto:' && Boolean(url.pathname);
  } catch {
    return false;
  }
}

export function normalizeReviewLink(value: string): string | null {
  const trimmed = value.trim();
  const url = /^[a-z][a-z\d+.-]*:/i.test(trimmed) ? trimmed : `https://${trimmed}`;
  return isReviewLinkAllowed(url) ? url : null;
}

export function reviewEditorExtensions() {
  return [
    StarterKit.configure({ codeBlock: false, blockquote: false, horizontalRule: false, strike: false, link: false }),
    Link.configure({
      openOnClick: false,
      autolink: true,
      defaultProtocol: 'https',
      HTMLAttributes: { target: '_blank', rel: 'noopener noreferrer nofollow' },
      isAllowedUri: (url, context) => context.defaultValidate(url) && isReviewLinkAllowed(url)
    })
  ];
}
