const { processRequest } = require("./apirequestmodule");

/**
 * Normalize line endings.
 * mode: 'preserve' | 'lf' | 'crlf'
 */
function normalizeBody(raw, mode = "preserve") {
  if (raw == null) return "";
  if (typeof raw !== "string") return JSON.stringify(raw);

  if (mode === "lf") {
    return raw.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
  }
  if (mode === "crlf") {
    let s = raw.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
    return s.replace(/\n/g, "\r\n");
  }
  return raw; // preserve
}

function buildRequest(rawPayload, { lineEndings = "preserve" } = {}) {
  const normalized = normalizeBody(rawPayload, lineEndings);
  return processRequest(normalized); // gives { headers, body }
}

module.exports = {
  buildRequest,
  normalizeBody,
};
