import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'

/**
 * 后端统一响应格式
 * code === 0 表示成功，data 为业务数据
 */
export interface ApiResult<T = any> {
  code: number
  message?: string
  data: T
}

const service: AxiosInstance = axios.create({
  // Use a relative path; Vite proxies /modelTF to http://localhost:17861 in local development.
  baseURL: '/modelTF',
  timeout: 30000,
})

// 请求拦截器
service.interceptors.request.use(
  (config) => config,
  (error) => Promise.reject(error),
)

// 响应拦截器：统一解包 { code, data, message }
service.interceptors.response.use(
  (response) => {
    const res = response.data as ApiResult
    // 二进制流等非 JSON 响应直接返回
    if (response.config.responseType === 'blob' || response.config.responseType === 'arraybuffer') {
      return response
    }
    if (res.code === 0) {
      return res.data
    }
    // 业务错误
    const message = res.message || '请求失败'
    ElMessage.error(message)
    return Promise.reject(new Error(message))
  },
  (error) => {
    const detail = error.response?.data?.detail
    const message = detail?.message || error.response?.data?.message || detail || error.message || '网络异常'
    ElMessage.error(message)
    return Promise.reject(error)
  },
)

/** GET 请求，返回已解包的 data */
export function get<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
  return service.get(url, { params, ...config }) as unknown as Promise<T>
}

/** POST 请求 */
export function post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
  return service.post(url, data, config) as unknown as Promise<T>
}

/** PUT 请求 */
export function put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
  return service.put(url, data, config) as unknown as Promise<T>
}

/** DELETE 请求 */
export function del<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
  return service.delete(url, { params, ...config }) as unknown as Promise<T>
}

export default service
