import { ref } from 'vue'
import api from '../services/api'

export function useFileUpload() {
  const uploading = ref(false)
  const processing = ref(false)
  const progress = ref(0)

  async function uploadFile(file: File, tableName: string, sheetName = '0') {
    uploading.value = true
    processing.value = false
    progress.value = 0

    const formData = new FormData()
    formData.append('file', file)
    formData.append('table_name', tableName)
    formData.append('sheet_name', sheetName)

    try {
      const { data } = await api.post('/import', formData, {
        timeout: 600000,  // 10 min — large files need time for type inference + insert + LLM enrichment
        onUploadProgress: (e) => {
          if (e.total) {
            const pct = Math.round((e.loaded / e.total) * 100)
            progress.value = pct
            if (pct >= 100) {
              processing.value = true
            }
          }
        },
      })
      return data
    } finally {
      uploading.value = false
      processing.value = false
    }
  }

  async function getSheets(file: File): Promise<string[]> {
    const formData = new FormData()
    formData.append('file', file)
    const { data } = await api.post('/import/sheets', formData)
    return data.sheets || []
  }

  return { uploading, processing, progress, uploadFile, getSheets }
}
