import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 15000,
  headers: { 'Content-Type': 'application/json' }
})

request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('admin_token')
    if (token) config.headers.Authorization = `Bearer ${token}`
    return config
  },
  error => Promise.reject(error)
)

request.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 0 || res.code === 200) return res
    ElMessage.error(res.message || '请求失败')
    return Promise.reject(new Error(res.message || '请求失败'))
  },
  error => {
    if (error.response) {
      const { status } = error.response
      if (status === 401) {
        localStorage.removeItem('admin_token')
        router.push('/login')
        ElMessage.error('登录已过期，请重新登录')
      } else if (status === 403) ElMessage.error('没有权限')
      else if (status >= 500) ElMessage.error('服务器错误')
    } else ElMessage.error('网络错误')
    return Promise.reject(error)
  }
)

// ====== 完全对齐后端实际路由 ======
export const authApi = {
  login(data) { return request.post('/admin/login', data) },
  getCaptcha() { return request.get('/admin/captcha') },
  logout() { return request.post('/admin/logout') }
}

export const dashboardApi = {
  getStats() { return request.get('/admin/dashboard/stats') },
  getOrderTrend(days = 7) { return request.get(`/admin/dashboard/order-trend?days=${days}`) }
}

export const productApi = {
  getList(params) { return request.get('/admin/products', { params }) },
  getDetail(id) { return request.get(`/admin/products/${id}`) },
  create(data) { return request.post('/admin/products', data) },
  update(id, data) { return request.put(`/admin/products/${id}`, data) },
  remove(id) { return request.delete(`/admin/products/${id}`) },
  toggleStatus(id, status) { return request.post(`/admin/products/${id}/status`, { status }) },
  duplicate(id) { return request.post(`/admin/products/${id}/copy`) }
}

export const orderApi = {
  getList(params) { return request.get('/admin/orders', { params }) },
  getDetail(orderNo) { return request.get(`/admin/orders/${orderNo}`) },
  ship(id, data) { return request.post(`/admin/orders/${id}/ship`, data) },
  cancel(orderNo) { return request.post(`/admin/orders/${orderNo}/cancel`) },
  complete(orderNo) { return request.post(`/admin/orders/${orderNo}/complete`) }
}

export const userApi = {
  getList(params) { return request.get('/admin/users', { params }) },
  update(id, data) { return request.put(`/admin/users/${id}`, data) },
  getLevels() { return request.get('/admin/levels') },
  saveLevel(data) { return request.post('/admin/levels', data) },
  updateLevel(id, data) { return request.put(`/admin/levels/${id}`, data) },
  deleteLevel(id) { return request.delete(`/admin/levels/${id}`) },
  getPlans() { return request.get('/admin/plans') },
  savePlan(data) { return request.post('/admin/plans', data) },
  updatePlan(id, data) { return request.put(`/admin/plans/${id}`, data) },
  deletePlan(id) { return request.delete(`/admin/plans/${id}`) }
}

export const aiApi = {
  getKnowledge(params) { return request.get('/admin/knowledge', { params }) },
  createKnowledge(data) { return request.post('/admin/knowledge', data) },
  updateKnowledge(id, data) { return request.put(`/admin/knowledge/${id}`, data) },
  deleteKnowledge(id) { return request.delete(`/admin/knowledge/${id}`) },
  importKnowledge(items) { return request.post('/admin/knowledge/import', { items }) }
}

export default request
