import { fetchWithAuth } from "./client";

// ── 类型定义 ────────────────────────────────────────────────────────────────────

export interface KnowledgeBase {
  id: string;
  name: string;
  type: "industry" | "enterprise";
  description?: string;
  document_count: number;
  status: string;
  created_at: string;
}

export interface KnowledgeDocument {
  id: string;
  title: string;
  source_type: "text" | "url" | "markdown";
  source_url?: string;
  chunk_count: number;
  status: "processing" | "ready" | "failed";
  error_message?: string;
  created_at: string;
}

export interface SearchResult {
  chunk_id: string;
  content: string;
  score: number;
  document_id: string;
  document_title: string;
  metadata: Record<string, unknown>;
}

export interface SearchResponse {
  results: SearchResult[];
  total: number;
  latency_ms: number;
}

export interface CreateKnowledgeBasePayload {
  name: string;
  type: string;
  description?: string;
}

export interface UploadDocumentPayload {
  title: string;
  source_type: string;
  content?: string;
  source_url?: string;
}

export const knowledgeApi = {
  listBases: (token?: string, type?: string) =>
    fetchWithAuth(
      `/api/v1/knowledge/bases/${type ? `?type=${type}` : ""}`,
      {},
      token
    ) as Promise<KnowledgeBase[]>,

  getBase: (token?: string, kbId?: string) =>
    fetchWithAuth(
      `/api/v1/knowledge/bases/${kbId}`,
      {},
      token
    ) as Promise<KnowledgeBase>,

  createBase: (token?: string, data?: CreateKnowledgeBasePayload) =>
    fetchWithAuth(
      "/api/v1/knowledge/bases/",
      { method: "POST", body: JSON.stringify(data) },
      token
    ) as Promise<KnowledgeBase>,

  deleteBase: (token?: string, kbId?: string) =>
    fetchWithAuth(
      `/api/v1/knowledge/bases/${kbId}`,
      { method: "DELETE" },
      token
    ),

  listDocuments: (token?: string, kbId?: string) =>
    fetchWithAuth(
      `/api/v1/knowledge/bases/${kbId}/documents`,
      {},
      token
    ) as Promise<KnowledgeDocument[]>,

  uploadDocument: (token?: string, kbId?: string, data?: UploadDocumentPayload) =>
    fetchWithAuth(
      `/api/v1/knowledge/bases/${kbId}/documents`,
      { method: "POST", body: JSON.stringify(data) },
      token
    ) as Promise<KnowledgeDocument>,

  deleteDocument: (token?: string, kbId?: string, docId?: string) =>
    fetchWithAuth(
      `/api/v1/knowledge/bases/${kbId}/documents/${docId}`,
      { method: "DELETE" },
      token
    ),

  search: (token?: string, query?: string, kbIds?: string[], topK?: number) =>
    fetchWithAuth(
      `/api/v1/knowledge/search`,
      {
        method: "POST",
        body: JSON.stringify({
          query,
          kb_ids: kbIds,
          top_k: topK,
        }),
      },
      token
    ) as Promise<SearchResponse>,
};
