function getCsrf() {
  return document.querySelector('meta[name="csrf-token"]')?.content ?? ''
}

async function request(path, options = {}) {
  const res = await fetch(path, {
    ...options,
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      'X-CSRF-TOKEN': getCsrf(),
      'X-Requested-With': 'XMLHttpRequest',
      ...(options.headers ?? {}),
    },
  })

  if (res.status === 401) {
    window.location.href = '/login'
    throw new Error('Unauthorized')
  }

  const json = await res.json()
  if (!res.ok) throw json
  return json?.data !== undefined ? json.data : json
}

export const api = {
  wallet: {
    balance: () => request('/api/v1/wallet/balance'),
    transactions: (page = 1, limit = 20) =>
      request(`/api/v1/wallet/transactions?page=${page}&limit=${limit}`),
    switchAccount: (account_type) =>
      request('/api/v1/wallet/switch-account', {
        method: 'PUT',
        body: JSON.stringify({ account_type }),
      }),
    withdrawalStatus: () => request('/api/v1/wallet/withdrawal-status'),
  },

  coupons: {
    claim: (code) =>
      request('/api/v1/coupons/claim', {
        method: 'POST',
        body: JSON.stringify({ code }),
      }),
  },

  trades: {
    open: (payload) =>
      request('/api/v1/trades/open', {
        method: 'POST',
        body: JSON.stringify(payload),
      }),
    settleExpired: () =>
      request('/api/v1/trades/settle-expired', { method: 'POST' }),
    active: () => request('/api/v1/trades/active'),
    history: (page = 1, limit = 20) =>
      request(`/api/v1/trades/history?page=${page}&limit=${limit}`),
    stats: () => request('/api/v1/trades/statistics'),
    get: (uuid) => request(`/api/v1/trades/${uuid}`),
  },
}
