import { request, authHeader, BASE } from "./client";

export const listKnowledgeBases = (token) =>
  request("GET", "/knowledge", token);

export const createKnowledgeBase = (token, name, description = "") =>
  request("POST", "/knowledge", token, { name, description });

export const getKnowledgeBase = (token, kbId) =>
  request("GET", `/knowledge/${kbId}`, token);

export const updateKnowledgeBase = (token, kbId, data) =>
  request("PUT", `/knowledge/${kbId}`, token, data);

export const deleteKnowledgeBase = (token, kbId) =>
  request("DELETE", `/knowledge/${kbId}`, token);

export const listKnowledgeDocuments = (token, kbId) =>
  request("GET", `/knowledge/${kbId}/documents`, token);

export const deleteKnowledgeDocument = (token, kbId, docId) =>
  request("DELETE", `/knowledge/${kbId}/documents/${docId}`, token);

export async function uploadDocuments(token, kbId, files) {
  const form = new FormData();
  for (const file of files) form.append("files", file);
  const res = await fetch(`${BASE}/knowledge/${kbId}/upload`, {
    method: "POST", headers: authHeader(token), body: form,
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.detail || "Upload failed");
  }
  return res.json();
}

export const uploadDocument = (token, kbId, file) =>
  uploadDocuments(token, kbId, [file]);
