/**
 * Helpers for the websocket chat error payloads sent by the backend
 * (see chat_backend/consumers.py — `{"type": "error", "code": ..., "content": ..., "details": {...}}`).
 */
export type ChatErrorPayload = {
  type?: string;
  code?: string;
  content?: string;
  message?: string;
  details?: Record<string, unknown> | null;
};

/** Parses a raw websocket text chunk into an error payload, or null when it isn't one. */
export function parseChatErrorPayload(message: string): ChatErrorPayload | null {
  try {
    const parsed = JSON.parse(message);
    if (parsed && typeof parsed === 'object' && parsed.type === 'error') {
      return parsed as ChatErrorPayload;
    }
  } catch {
    /* not JSON — plain streamed text chunk */
  }
  return null;
}

/** True when a `feature_not_allowed` error payload is about the RAG (document search) feature. */
export function isRagFeatureNotAllowed(payload: ChatErrorPayload | null | undefined): boolean {
  if (!payload || payload.code !== 'feature_not_allowed') {
    return false;
  }
  const feature = payload.details?.feature;
  if (typeof feature === 'string' && feature.toLowerCase().includes('rag')) {
    return true;
  }
  const text = `${payload.content ?? ''} ${payload.message ?? ''}`.toLowerCase();
  return text.includes('rag');
}
