import axios from 'axios'

const apiBaseURL =
  import.meta.env.VITE_API_BASE_URL ||
  import.meta.env.VITE_API_BASE ||
  (typeof window !== 'undefined' ? window.location.origin : 'http://localhost:8080')

const api = axios.create({
  baseURL: apiBaseURL
})

// 管理员请求头构建辅助函数，使用 X-Admin-Token 请求头。
// 后端保留 ?token= 查询参数作为旧版兼容，新请求统一使用请求头以兼容 Spring Security。
const adminHeaders = (token) => ({ 'X-Admin-Token': token })

const authApi = axios.create({
  baseURL: 'https://auth.api.shumengya.top'
})

export const fetchProducts = async () => {
  const { data } = await api.get('/api/products')
  return data.data || []
}

export const recordProductView = async (id) => {
  const { data } = await api.post(`/api/products/${id}/view`)
  return data.data || {}
}

export const createOrder = async (payload, authToken) => {
  const headers = authToken ? { Authorization: `Bearer ${authToken}` } : {}
  const { data } = await api.post('/api/checkout', payload, { headers })
  return data.data || {}
}

export const confirmOrder = async (orderId) => {
  const { data } = await api.post(`/api/orders/${orderId}/confirm`)
  return data.data || {}
}

export const fetchStats = async () => {
  const { data } = await api.get('/api/stats')
  return data.data || {}
}

export const recordSiteVisit = async () => {
  const { data } = await api.post('/api/site/visit')
  return data.data || {}
}

export const verifySproutGateToken = async (token) => {
  const { data } = await authApi.post('/api/auth/verify', { token })
  return data
}

export const fetchSproutGateUser = async (token) => {
  const { data } = await authApi.get('/api/auth/me', {
    headers: { Authorization: `Bearer ${token}` }
  })
  return data
}

export const fetchMyOrders = async (authToken) => {
  const { data } = await api.get('/api/orders', {
    headers: { Authorization: `Bearer ${authToken}` }
  })
  return data.data || []
}

export const verifyAdminToken = async (token) => {
  const { data } = await api.post('/api/admin/verify', { token })
  return data.valid === true
}

export const fetchAdminProducts = async (token) => {
  const { data } = await api.get('/api/admin/products', { headers: adminHeaders(token) })
  return data.data || []
}

export const createProduct = async (token, payload) => {
  const { data } = await api.post('/api/admin/products', payload, {
    headers: adminHeaders(token)
  })
  return data.data
}

export const updateProduct = async (token, id, payload) => {
  const { data } = await api.put(`/api/admin/products/${id}`, payload, {
    headers: adminHeaders(token)
  })
  return data.data
}

export const toggleProduct = async (token, id, active) => {
  const { data } = await api.patch(`/api/admin/products/${id}/status`, { active }, {
    headers: adminHeaders(token)
  })
  return data.data
}

export const deleteProduct = async (token, id) => {
  const { data } = await api.delete(`/api/admin/products/${id}`, {
    headers: adminHeaders(token)
  })
  return data
}

export const fetchWishlist = async (token) => {
  const { data } = await api.get('/api/wishlist', {
    headers: { Authorization: `Bearer ${token}` }
  })
  return data.data?.items || []
}

export const addToWishlist = async (token, productId) => {
  const { data } = await api.post('/api/wishlist', { productId }, {
    headers: { Authorization: `Bearer ${token}` }
  })
  return data.data?.items || []
}

export const removeFromWishlist = async (token, productId) => {
  const { data } = await api.delete(`/api/wishlist/${productId}`, {
    headers: { Authorization: `Bearer ${token}` }
  })
  return data.data?.items || []
}

export const fetchAdminOrders = async (token) => {
  const { data } = await api.get('/api/admin/orders', { headers: adminHeaders(token) })
  return data.data || []
}

export const deleteAdminOrder = async (token, orderId) => {
  await api.delete(`/api/admin/orders/${orderId}`, { headers: adminHeaders(token) })
}

export const fetchSiteMaintenance = async () => {
  const { data } = await api.get('/api/site/maintenance')
  return data.data || { maintenance: false, reason: '' }
}

export const setSiteMaintenance = async (token, maintenance, reason) => {
  const { data } = await api.post('/api/admin/site/maintenance', { maintenance, reason }, {
    headers: adminHeaders(token)
  })
  return data.data || {}
}

// ---- SMTP Config ----
export const fetchSMTPConfig = async (token) => {
  const { data } = await api.get('/api/admin/site/smtp', { headers: adminHeaders(token) })
  return data.data || {}
}

export const setSMTPConfig = async (token, cfg) => {
  const { data } = await api.post('/api/admin/site/smtp', cfg, { headers: adminHeaders(token) })
  return data.data
}

// ---- Chat (user) ----
export const fetchMyChatMessages = async (userToken) => {
  const { data } = await api.get('/api/chat/messages', {
    headers: { Authorization: `Bearer ${userToken}` }
  })
  return data.data?.messages || []
}

export const sendChatMessage = async (userToken, content) => {
  const { data } = await api.post('/api/chat/messages', { content }, {
    headers: { Authorization: `Bearer ${userToken}` }
  })
  return data.data?.message || null
}

// ---- Chat (admin) ----
export const fetchAdminAllConversations = async (adminToken) => {
  const { data } = await api.get('/api/admin/chat', { headers: adminHeaders(adminToken) })
  return data.data?.conversations || {}
}

export const fetchAdminConversation = async (adminToken, account) => {
  const { data } = await api.get(`/api/admin/chat/${encodeURIComponent(account)}`, {
    headers: adminHeaders(adminToken)
  })
  return data.data?.messages || []
}

export const adminSendChatReply = async (adminToken, account, content) => {
  const { data } = await api.post(
    `/api/admin/chat/${encodeURIComponent(account)}`,
    { content },
    { headers: adminHeaders(adminToken) }
  )
  return data.data?.message || null
}

export const adminClearConversation = async (adminToken, account) => {
  await api.delete(`/api/admin/chat/${encodeURIComponent(account)}`, {
    headers: adminHeaders(adminToken)
  })
}

// ---- Admin system status（后端 / MySQL / Redis / RabbitMQ）----
export const fetchSystemStatus = async (adminToken) => {
  const { data } = await api.get('/api/admin/system-status', { headers: adminHeaders(adminToken) })
  return data.data || {}
}
