/**
 * Turn Frappe HTML validation messages into plain text for toasts and alerts.
 */
export function frappeHtmlToPlainText(html: string): string {
  if (!html || typeof html !== 'string') return '';
  let s = html
    .replace(/<br\s*\/?>/gi, '\n')
    .replace(/<\/(p|div|li|tr)>/gi, '\n')
    // Links may contain nested <strong> etc.; keep visible text only
    .replace(/<a[^>]*>([\s\S]*?)<\/a>/gi, (_, inner: string) =>
      inner.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim(),
    )
    .replace(/<[^>]+>/g, ' ');
  s = s
    .replace(/&nbsp;/g, ' ')
    .replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&#39;/g, "'")
    .replace(/&quot;/g, '"');
  return s.replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').replace(/  +/g, ' ').trim();
}

/** Parse Frappe API error body / thrown Error into a user-readable string (no raw HTML). */
export function formatFrappeApiError(err: unknown): string {
  if (err == null) return 'Something went wrong';
  if (err instanceof Error) return frappeHtmlToPlainText(err.message) || err.message;
  if (typeof err === 'string') return frappeHtmlToPlainText(err);
  const e = err as Record<string, unknown>;
  let msg = typeof e.message === 'string' ? e.message : '';
  if (e._server_messages) {
    try {
      const raw = e._server_messages;
      const arr = typeof raw === 'string' ? JSON.parse(raw) : raw;
      if (Array.isArray(arr)) {
        const parts: string[] = [];
        for (const item of arr) {
          try {
            const o = typeof item === 'string' ? JSON.parse(item) : item;
            if (o && typeof (o as { message?: string }).message === 'string') {
              parts.push(frappeHtmlToPlainText((o as { message: string }).message));
            } else if (typeof item === 'string') parts.push(frappeHtmlToPlainText(item));
          } catch {
            if (typeof item === 'string') parts.push(frappeHtmlToPlainText(item));
          }
        }
        if (parts.length) msg = parts.join('\n');
      }
    } catch {
      /* ignore */
    }
  }
  if (!msg && typeof e.exc === 'string' && e.exc.length < 800) msg = e.exc;
  if (!msg) return 'Request failed. Check stock, warehouses, and linked documents.';
  return frappeHtmlToPlainText(msg);
}
