import { unstable_cache } from 'next/cache';

import 'server-only';

import { hasRichTextContent, parseRichText } from '@/utils/richText';

const getBlockNoteHtml = unstable_cache(
  async (document: string) => {
    const { convertBlockNoteToHtml } = await import('./blocknote');
    return convertBlockNoteToHtml(document);
  },
  // Bump when upgrading BlockNote or changing the export/schema configuration.
  ['blocknote-html', '0.54.2', 'default-schema-v3'],
  { revalidate: false }
);

export async function renderRichText(value: unknown): Promise<string> {
  const parsed = parseRichText(value);
  if (parsed.format === 'html') return parsed.html;
  if (parsed.format === 'invalid') {
    console.error('Invalid BlockNote document in creator text content.');
    return '';
  }
  if (!hasRichTextContent(parsed.blocks)) return '';

  try {
    // The document is part of the cache key: an edit gets fresh HTML immediately.
    return await getBlockNoteHtml(JSON.stringify(parsed.blocks));
  } catch {
    // Do not break the creator page or expose raw JSON on unsupported/corrupt blocks.
    // Failed exports are not cached, so the next request can retry.
    console.error('Could not export creator BlockNote content using the default schema.');
    return '';
  }
}
