import axios from 'axios'
import type { AxiosInstance } from 'axios'
import type { Project, ProjectCreate, ProjectUpdate } from '@/types'

const request: AxiosInstance = axios.create({
  baseURL: import.meta.env.PROD
    ? '/api/v1'
    : 'http://10.10.10.77:8000/api/v1',
  timeout: 60000
})

// Request interceptor
request.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// Response interceptor
request.interceptors.response.use(
  response => {
    const data = response.data
    // Handle new ApiResponse format
    if (data.success !== undefined) {
      if (data.success) {
        return data.data // Return the actual data
      } else {
        return Promise.reject(new Error(data.message || data.error || '请求失败'))
      }
    }
    return data
  },
  error => {
    const message = error.response?.data?.message || error.message || '请求失败'
    console.error('API Error:', message)
    return Promise.reject(error)
  }
)

export const projectApi = {
  list: () => request.get<Project[]>('/projects/'),
  get: (id: string) => request.get<Project>(`/projects/${id}`),
  create: (data: ProjectCreate) => request.post<{ id: string }>('/projects/', data),
  update: (id: string, data: ProjectUpdate) => request.put<Project>(`/projects/${id}`, data),
  delete: (id: string) => request.delete(`/projects/${id}`)
}

export const fileApi = {
  upload: (projectId: string, formData: FormData) =>
    request.post(`/projects/${projectId}/files/upload`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    }),
  list: (projectId: string) => request.get(`/projects/${projectId}/files/`),
  get: (projectId: string, fileId: string) => request.get(`/projects/${projectId}/files/${fileId}`),
  delete: (projectId: string, fileId: string) => request.delete(`/projects/${projectId}/files/${fileId}`)
}

export const chunkApi = {
  split: (projectId: string, data: any) => request.post(`/projects/${projectId}/chunks/split`, data),
  list: (projectId: string, params?: any) => request.get(`/projects/${projectId}/chunks/`, { params }),
  get: (projectId: string, chunkId: string) => request.get(`/projects/${projectId}/chunks/${chunkId}`),
  update: (projectId: string, chunkId: string, data: any) => request.put(`/projects/${projectId}/chunks/${chunkId}`, data),
  delete: (projectId: string, chunkId: string) => request.delete(`/projects/${projectId}/chunks/${chunkId}`)
}

export const questionApi = {
  generate: (projectId: string, data: any) => request.post(`/projects/${projectId}/generate-questions`, data),
  list: (projectId: string, params: { chunkId: string }) => request.get(`/projects/${projectId}/chunks/${params.chunkId}/questions`),
  update: (projectId: string, questionId: string, data: any) => request.put(`/projects/${projectId}/questions/${questionId}`, data),
  delete: (projectId: string, questionId: string) => request.delete(`/projects/${projectId}/questions/${questionId}`)
}

export const datasetApi = {
  list: (projectId: string) => request.get(`/projects/${projectId}/datasets/`),
  create: (projectId: string, data: any) => request.post(`/projects/${projectId}/datasets/`, data),
  get: (projectId: string, datasetId: string) => request.get(`/projects/${projectId}/datasets/${datasetId}`),
  delete: (projectId: string, datasetId: string) => request.delete(`/projects/${projectId}/datasets/${datasetId}`),
  export: (projectId: string, datasetId: string, data: any) =>
    request.post(`/projects/${projectId}/datasets/${datasetId}/export`, data, {
      responseType: 'blob'
    })
}

export const evalApi = {
  list: (projectId: string) => request.get(`/projects/${projectId}/eval-datasets/`),
  create: (projectId: string, data: any) => request.post(`/projects/${projectId}/eval-datasets/`, data),
  run: (projectId: string, evalId: string) => request.post(`/projects/${projectId}/eval-datasets/${evalId}/evaluate`),
  getResults: (projectId: string, taskId: string) => request.get(`/projects/${projectId}/eval-tasks/${taskId}`)
}

export default request
