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
})

const adminHeaders = (token) => ({ 'X-Admin-Token': token })

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

/** 后端常规信封 `{ data: { data: T } }` 解包 */
function unwrapData(res) {
  return res?.data?.data
}

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

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

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

export const fetchOrderPaymentStatus = async (orderId) => {
  const res = await api.get(`/api/orders/${encodeURIComponent(orderId)}/payment-status`)
  return unwrapData(res) || {}
}

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

export const cancelOrder = async (orderId) => {
  const res = await api.post(`/api/orders/${orderId}/cancel`)
  return unwrapData(res) || {}
}

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

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

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 res = await api.get('/api/orders', {
    headers: { Authorization: `Bearer ${authToken}` }
  })
  return unwrapData(res) || []
}

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

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

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

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

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

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 res = await api.get('/api/wishlist', {
    headers: { Authorization: `Bearer ${token}` }
  })
  return unwrapData(res)?.items || []
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

export const fetchSystemStatus = async (adminToken) => {
  const res = await api.get('/api/admin/system-status', { headers: adminHeaders(adminToken) })
  return unwrapData(res) || {}
}
