const { request } = require('undici');
const config = require('../../config/default');

async function deliver(payload) {
  const body = JSON.stringify(payload);
  const start = Date.now();
  const headers = {
    'content-type': 'application/json'
  };
  if (config.clqms.token) {
    headers.authorization = `Bearer ${config.clqms.token}`;
  }
  const response = await request(config.clqms.url, {
    method: 'POST',
    headers,
    body,
    keepaliveTimeout: 0,
    bodyTimeout: config.clqms.timeout
  });
  const latency = Date.now() - start;
  const responseBody = await response.body.text();
  return {
    code: response.statusCode,
    body: responseBody,
    latency
  };
}

module.exports = { deliver };
