import axios from 'axios'

const client = axios.create({ baseURL: '' })

client.interceptors.request.use(config => {
  const token = localStorage.getItem('manager_token')
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
})

client.interceptors.response.use(
  res => res,
  err => {
    if (err.response?.status === 401) {
      // On hard 401 (expired/invalid token) force a full logout
      localStorage.removeItem('manager_token')
      localStorage.removeItem('manager_username')
      localStorage.removeItem('manager_lock_timeout')
      window.location.href = '/login'
    }
    return Promise.reject(err)
  }
)

export default client

// ── Online Orders (Xenia Connect) ─────────────────────────────────────────────

export const getIncomingOrders = () => client.get('/api/connect/orders/incoming')
export const getActiveOrders   = () => client.get('/api/connect/orders?status=active')
export const getOrderHistory   = () => client.get('/api/connect/orders?status=history')

export const acceptOnlineOrder = (id) =>
  client.post(`/api/connect/orders/${id}/accept`)

export const rejectOnlineOrder = (id, reason) =>
  client.post(`/api/connect/orders/${id}/reject`, { reason })

export const updateOnlineOrderStatus = (id, status) =>
  client.post(`/api/connect/orders/${id}/status`, { status })
