import axios from 'axios'
import { handleAuthError } from './auth.js'

const API_BASE_URL = '/api'

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json'
  }
})

apiClient.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 对于文件预览/下载请求，确保不触发浏览器下载
    if (config.url?.includes('/preview/') || config.url?.includes('/download/') || config.url?.includes('/content/')) {
      config.responseType = 'blob'
      // 防止浏览器自动下载
      config.headers['Accept'] = '*/*'
    }
    
    return config
  },
  error => Promise.reject(error)
)

apiClient.interceptors.response.use(
  response => {
    // 对于 Blob 响应，检查是否成功
    if (response.config.responseType === 'blob') {
      // 如果返回的是 JSON 错误（比如后端返回的错误信息）
      if (response.data.type && response.data.type.includes('application/json')) {
        return response.data.text().then(text => {
          const jsonData = JSON.parse(text)
          return Promise.reject({ 
            response: { 
              data: jsonData, 
              status: response.status 
            } 
          })
        })
      }
    }
    return response
  },
  error => {
    const status = error.response?.status
    if (status === 401 || status === 403) {
      handleAuthError()
      return Promise.reject(error)
    }
    return Promise.reject(error)
  }
)

export const fileAPI = {
  getFiles: (params = {}) => {
    return apiClient.get('/file/page', { params })
  },

  uploadFile: (formData, onProgress, options = {}) => {
    if (options.autoVectorize) {
      formData.append('autoVectorize', 'true')
    }
    if (options.collectionName) {
      formData.append('collectionName', options.collectionName)
    }
    return apiClient.post('/file/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        if (typeof onProgress === 'function' && progressEvent.total) {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )

          onProgress({
            loaded: progressEvent.loaded,
            total: progressEvent.total,
            percent: percentCompleted,
            estimatedTimeRemaining: null
          })
        }
      }
    })
  },

  getFileDetail: (id) => {
    return apiClient.get(`/file/${id}`)
  },

  updateFile: (id, data) => {
    return apiClient.put(`/file/${id}`, data)
  },

  deleteFile: (id) => {
    return apiClient.delete(`/file/${id}`)
  },

  getPendingFiles: (params = {}) => {
    return apiClient.get('/file/audit/pending', { params })
  },

  approveFile: (id) => {
    return apiClient.post(`/file/audit/approve/${id}`)
  },

  rejectFile: (id) => {
    return apiClient.post(`/file/audit/reject/${id}`)
  },

  getFileContent: (id) => {
    return apiClient.get(`/file/content/${id}`, {
      responseType: 'blob'
    })
  },

  previewFile: (id) => {
    return apiClient.get(`/file/preview/${id}`, {
      responseType: 'blob'
    })
  },

  getTextFileContent: (id) => {
    return apiClient.get(`/file/text/${id}`)
  },

  downloadFile: (id) => {
    return apiClient.get(`/file/download/${id}`, {
      responseType: 'blob'
    })
  },

  getFileInfo: (id) => {
    return apiClient.get(`/file/info/${id}`)
  }
}

// 注意：由于axios的onUploadProgress不提供时间戳信息，
// 精确的剩余时间估算需要在外部通过 performance.now() 手动记录
// 这里简化处理，estimatedTimeRemaining 统一返回 null
// 如需此功能，建议在调用方维护一个时间戳映射表

export default fileAPI
