import { apiRequest } from './api.js'

export function fetchKnowledgeLibrary() {
  return apiRequest('/knowledge/library')
}

export function fetchKnowledgeDocument(documentId) {
  return apiRequest(`/knowledge/documents/${documentId}`)
}

export function fetchKnowledgeOnlyOfficeConfig(documentId) {
  return apiRequest(`/knowledge/documents/${documentId}/onlyoffice-config`)
}

export function uploadKnowledgeDocument({ folder, file }) {
  return apiRequest(
    `/knowledge/documents?folder=${encodeURIComponent(folder)}&filename=${encodeURIComponent(file.name)}`,
    {
      method: 'POST',
      body: file,
      contentType: file.type || 'application/octet-stream'
    }
  )
}

export function deleteKnowledgeDocument(documentId) {
  return apiRequest(`/knowledge/documents/${documentId}`, {
    method: 'DELETE'
  })
}

export function syncKnowledgeLibrary({ folder, documentIds = [], force = false }) {
  return apiRequest('/knowledge/sync', {
    method: 'POST',
    body: JSON.stringify({
      folder,
      document_ids: Array.isArray(documentIds) ? documentIds : [],
      force
    })
  })
}

export function fetchKnowledgeDocumentBlob(documentId, disposition = 'inline') {
  return apiRequest(`/knowledge/documents/${documentId}/content?disposition=${disposition}`, {
    responseType: 'blob',
    contentType: null
  })
}
