function getConfig() {
  return {
    baseUrl: process.env.SMARTCOIN_API_BASE || "http://127.0.0.1:8000",
    adminToken: process.env.ADMIN_TOKEN || "test-token",
  };
}

async function request(path, options = {}) {
  const config = getConfig();
  const separator = path.includes("?") ? "&" : "?";
  const url = `${config.baseUrl}${path}${separator}token=${encodeURIComponent(config.adminToken)}`;
  let response;
  try {
    response = await fetch(url, {
      headers: {
        "Content-Type": "application/json",
        ...(options.headers || {}),
      },
      ...options,
    });
  } catch (error) {
    const cause = error.cause?.message || error.message;
    throw new Error(`Cannot reach SmartCoin API at ${config.baseUrl}: ${cause}`);
  }
  const payload = await response.json();
  if (!response.ok) {
    throw new Error(payload.error || `Request failed with HTTP ${response.status}`);
  }
  return payload;
}

module.exports = {
  request,
};
