import axios from 'axios'

const apiBaseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'

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

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 fetchAdminToken = async () => {
  const { data } = await api.get('/api/admin/token')
  return data.token || ''
}

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

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

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

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

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