import api from './index'

export interface Document {
  id: string
  title: string
  filename: string
  file_type: string
  file_size: number
  summary?: string
  chunk_count: number
  is_indexed: boolean
  ingestion_status?: 'uploaded' | 'parsing' | 'indexing' | 'ready' | 'warning' | 'failed'
  ingestion_error?: string | null
  indexed_at?: string | null
  parser_version?: string | null
  index_version?: string | null
  folder_id?: string | null
  created_at: string
}

export interface DocumentChunk {
  id: string
  chunk_index: number
  content: string
  metadata_?: string | null
}

export interface DocumentChunkUpdate {
  content: string
}

export interface SearchResult {
  chunk_id: string
  document_id: string
  document_title: string
  content: string
  score: number
  metadata_?: string
  prev_chunk?: string
  next_chunk?: string
}

export interface UploadResponse {
  id: string
  title: string
  chunk_count: number
  status: string
  ingestion_status?: 'uploaded' | 'parsing' | 'indexing' | 'ready' | 'warning' | 'failed'
  ingestion_error?: string | null
  indexed_at?: string | null
}

export const documentApi = {
  list(folderId?: string | null) {
    return api.get<Document[]>('/api/documents', {
      params: folderId ? { folder_id: folderId } : undefined,
    })
  },

  upload(file: File, folderId?: string | null) {
    const formData = new FormData()
    formData.append('file', file)
    if (folderId) {
      formData.append('folder_id', folderId)
    }
    return api.post<UploadResponse>('/api/documents/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
  },

  get(id: string) {
    return api.get<Document>(`/api/documents/${id}`)
  },

  getChunks(id: string) {
    return api.get<DocumentChunk[]>(`/api/documents/${id}/chunks`)
  },

  updateChunk(documentId: string, chunkId: string, payload: DocumentChunkUpdate) {
    return api.put<DocumentChunk>(`/api/documents/${documentId}/chunks/${chunkId}`, payload)
  },

  delete(id: string) {
    return api.delete(`/api/documents/${id}`)
  },

  search(query: string, top_k = 5, mode = 'hybrid') {
    return api.get<SearchResult[]>('/api/documents/search', {
      params: { query, top_k, mode },
    })
  },

  getContent(id: string) {
    return api.get<string>(`/api/documents/${id}/content`)
  },
}
