import axios from 'axios'
import { getTokenFromCookie, getUserIdFromCookie } from '@/utils/cookie'

const API_BASE_URL = 'http://101.126.85.76:8002/api/v1'
console.log('API_BASE_URL:',API_BASE_URL)
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 从cookie中获取token和userId
    const token = getTokenFromCookie()
    const userId = getUserIdFromCookie()

    // 如果token不存在，尝试从localStorage获取（兼容性）
    const fallbackToken = localStorage.getItem('access_token')
    const finalToken = token || fallbackToken

    if (finalToken) {
      config.headers.Authorization = `Bearer ${finalToken}`
      config.headers.token = finalToken
    }

    if (userId) {
      config.headers.userId = userId.toString()
    }

    return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截器
api.interceptors.response.use(
  (response) => response.data,
  (error) => {
    if (error.response?.status === 401) {
      // 清除localStorage中的token
      localStorage.removeItem('access_token')
      localStorage.removeItem('refresh_token')

      // 导入并清除cookie
      import('@/utils/cookie').then(({ clearAuthCookies }) => {
        clearAuthCookies()
      })

      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export const healthAPI = {
  checkHealth: () => api.get('/health'),
  checkReadiness: () => api.get('/ready'),
}

// 文件相关API
// 认证相关API
export const authAPI = {
  // 用户注册
  register: (userData: {
    username: string
    email: string
    password: string
    confirm_password: string
  }) => {
    return api.post('/auth/register', userData)
  },

  // 用户登录
  login: (credentials: {
    username: string
    password: string
  }) => {
    return api.post('/auth/login', credentials)
  },

  // 刷新令牌
  refreshToken: (refreshToken: string) => {
    return api.post('/auth/refresh', { refresh_token: refreshToken })
  },

  // 获取当前用户信息
  getCurrentUser: () => {
    return api.get('/auth/me')
  },

  // 用户登出
  logout: () => {
    return api.post('/auth/logout')
  },
}

// 文件相关API
export const filesAPI = {
  // 上传文件
  uploadFile: (formData: FormData) => {
    return api.post('/files/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
  },

  // 获取文件列表 - 现在使用Query参数而不是POST body
  getFiles: (page: number = 1, size: number = 10) => {
    return api.get('/files/list', {
      params: { page, size }
    })
  },

  // 获取文件信息
  getFileInfo: (fileId: number, userId: number) => {
    return api.post('/files/info', { file_id: fileId, user_id: userId })
  },

  // 更新文件信息
  updateFile: (fileId: number, userId: number, updateData: any) => {
    return api.post('/files/update', {
      file_id_request: { file_id: fileId, user_id: userId },
      update_request: updateData
    })
  },

  // 删除文件
  deleteFile: (fileId: number, userId: number) => {
    return api.post('/files/delete', { file_id: fileId, user_id: userId })
  },

  // 下载文件
  downloadFile: (fileId: number, userId: number) => {
    return api.post('/files/download', { file_id: fileId, user_id: userId }, {
      responseType: 'blob',
    })
  },

  // 获取存储信息
  getStorageInfo: (userId: number) => {
    return api.post('/files/storage/info', { user_id: userId })
  },
}

export default api