import apiClient from './client'
import type {
  KBUploadResponse,
  KBImport,
  KBImportListResponse,
  KBImportNode,
  KBCommitResponse,
  KBQuotaResponse,
  KBListParams,
  KBNodeEditRequest,
  KBCommitRequest,
} from '@/types/kbAccelerator'

export const kbAcceleratorApi = {
  async uploadText(data: { content: string; title?: string; target_type?: string }): Promise<KBUploadResponse> {
    const formData = new FormData()
    formData.append('content', data.content)
    if (data.title) formData.append('title', data.title)
    if (data.target_type) formData.append('target_type', data.target_type)

    const response = await apiClient.post<KBUploadResponse>('/kb-accelerator/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    return response.data
  },

  async uploadFile(file: File, targetType?: string): Promise<KBUploadResponse> {
    const formData = new FormData()
    formData.append('file', file)
    if (targetType) formData.append('target_type', targetType)

    const response = await apiClient.post<KBUploadResponse>('/kb-accelerator/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    return response.data
  },

  async get(id: string): Promise<KBImport> {
    const response = await apiClient.get<KBImport>(`/kb-accelerator/${id}`)
    return response.data
  },

  async list(params?: KBListParams): Promise<KBImportListResponse> {
    const response = await apiClient.get<KBImportListResponse>('/kb-accelerator', { params })
    return response.data
  },

  async convert(id: string): Promise<{ status: string }> {
    const response = await apiClient.post<{ status: string }>(`/kb-accelerator/${id}/convert`)
    return response.data
  },

  async editNode(importId: string, nodeId: string, data: KBNodeEditRequest): Promise<KBImportNode> {
    const response = await apiClient.patch<KBImportNode>(
      `/kb-accelerator/${importId}/nodes/${nodeId}`,
      data,
    )
    return response.data
  },

  async commit(id: string, data?: KBCommitRequest): Promise<KBCommitResponse> {
    const response = await apiClient.post<KBCommitResponse>(`/kb-accelerator/${id}/commit`, data)
    return response.data
  },

  async delete(id: string): Promise<void> {
    await apiClient.delete(`/kb-accelerator/${id}`)
  },

  async getQuota(): Promise<KBQuotaResponse> {
    const response = await apiClient.get<KBQuotaResponse>('/kb-accelerator/quota')
    return response.data
  },
}

export default kbAcceleratorApi
