/**
 * 内容工坊页面数据获取 Hook
 *
 * 封装内容列表 + 知识库列表的 SWR 请求，替代手动 useState + useEffect 模式。
 * 两个请求并行发出，无数据依赖。
 */

import { useApi } from "./use-api";
import type { SWRConfiguration } from "swr";
import type { Content } from "@/lib/api/contents";
import type { KnowledgeBase } from "@/lib/api/knowledge";

export interface UseContentDataReturn {
  /** 内容列表 */
  contents: Content[] | undefined;
  /** 知识库列表 */
  knowledgeBases: KnowledgeBase[] | undefined;
  /** 是否正在加载（任一请求加载中） */
  isLoading: boolean;
  /** 错误信息 */
  error: Error | undefined;
  /** 刷新内容列表 */
  refreshContents: () => void;
  /** 刷新知识库列表 */
  refreshKnowledgeBases: () => void;
}

export interface UseContentDataOptions {
  /** SWR 配置（用于测试时禁用重试等） */
  swrOptions?: SWRConfiguration;
}

export function useContentData(
  options?: UseContentDataOptions
): UseContentDataReturn {
  const swrOptions = options?.swrOptions;

  // 内容列表
  const {
    data: contents,
    isLoading: contentsLoading,
    error: contentsError,
    refresh: refreshContents,
  } = useApi<Content[]>("/api/v1/contents/", swrOptions);

  // 知识库列表（仅获取 enterprise 类型）
  const {
    data: knowledgeBases,
    isLoading: kbLoading,
    error: kbError,
    refresh: refreshKnowledgeBases,
  } = useApi<KnowledgeBase[]>("/api/v1/knowledge/bases/?type=enterprise", swrOptions);

  const isLoading = contentsLoading || kbLoading;
  const error = contentsError || kbError;

  return {
    contents,
    knowledgeBases,
    isLoading,
    error,
    refreshContents,
    refreshKnowledgeBases,
  };
}
