import type { Json } from "@/types/supabase";

/**
 * 提取文档内容中的块数组，兼容数组和 { blocks: [] } 两种结构。
 */
export const extractBlocksFromContent = (content: unknown): Json[] => {
  if (Array.isArray(content)) {
    return content as Json[];
  }
  if (content && typeof content === "object" && Array.isArray((content as { blocks?: Json[] }).blocks)) {
    return ((content as { blocks?: Json[] }).blocks ?? []) as Json[];
  }
  return [];
};

/**
 * 将新的块数组写回内容，保持原有结构额外字段。
 */
export const composeContentWithBlocks = (content: unknown, blocks: Json[]): Json => {
  if (Array.isArray(content)) {
    return blocks as Json;
  }
  if (content && typeof content === "object") {
    return {
      ...(content as Record<string, unknown>),
      blocks,
    } as Json;
  }
  return { blocks } as Json;
};
