import { ServerBlockNoteEditor } from '@blocknote/server-util';
import 'server-only';

let editor: ServerBlockNoteEditor | undefined;
let pending: Promise<unknown> = Promise.resolve();

function readSafeDocument(document: string) {
  return JSON.parse(document, (key, value: unknown) => {
    // The default file/media exporters copy URLs directly into HTML attributes.
    // Inline link validation alone does not protect those blocks.
    if ((key === 'url' || key === 'href') && typeof value === 'string') {
      try {
        const { protocol } = new URL(value, 'https://azopus.hu');
        return ['http:', 'https:', 'mailto:', 'tel:'].includes(protocol) ? value : '';
      } catch {
        return '';
      }
    }
    return value;
  }) as Parameters<ServerBlockNoteEditor['blocksToHTMLLossy']>[0];
}

/** Loaded only on a BlockNote HTML cache miss. Uses the default editor schema. */
export function convertBlockNoteToHtml(document: string): Promise<string> {
  // server-util temporarily changes global window/document while exporting.
  // Serialize exports in this process so concurrent requests cannot interfere.
  const result = pending.then(async () => {
    editor ??= ServerBlockNoteEditor.create();
    const html = await editor.blocksToHTMLLossy(readSafeDocument(document));
    return html
      // BlockNote marks empty inline blocks with U+FFFC for HTML round trips.
      // Public HTML needs a line break instead of the visible OBJ placeholder.
      .replaceAll('>\uFFFC<', '><br><')
      .replaceAll('<input type="checkbox"', '<input type="checkbox" disabled');
  });
  pending = result.catch(() => undefined);
  return result;
}
