import axios from 'axios'
import type { QueryRequest, QueryResponse, IngestResponse, DocumentListResponse, ChunkInfo, DeleteResponse } from '../types'

const BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:8000/api/v1'

export const apiClient = axios.create({ baseURL: BASE_URL })

export const queryDocument = async (request: QueryRequest): Promise<QueryResponse> => {
  const resp = await apiClient.post<QueryResponse>('/query', request)
  return resp.data
}

export const ingestDocument = async (file: File): Promise<IngestResponse> => {
  const form = new FormData()
  form.append('file', file)
  const resp = await apiClient.post<IngestResponse>('/ingest', form, {
    headers: { 'Content-Type': 'multipart/form-data' },
  })
  return resp.data
}

export const listDocuments = async (): Promise<DocumentListResponse> => {
  const resp = await apiClient.get<DocumentListResponse>('/documents')
  return resp.data
}

export const listChunks = async (documentId: string): Promise<ChunkInfo[]> => {
  const resp = await apiClient.get<ChunkInfo[]>(`/documents/${documentId}/chunks`)
  return resp.data
}

export const deleteDocument = async (documentId: string): Promise<DeleteResponse> => {
  const resp = await apiClient.delete<DeleteResponse>(`/documents/${documentId}`)
  return resp.data
}

export const deleteChunk = async (chunkId: string): Promise<DeleteResponse> => {
  const resp = await apiClient.delete<DeleteResponse>(`/chunks/${chunkId}`)
  return resp.data
}
