const { safeErrorMessage } = require("./redaction");

function formatExtra(extra = {}) {
  return Object.entries(extra)
    .filter(([, value]) => value !== undefined && value !== null && value !== "")
    .map(([key, value]) => `${key}=${String(value)}`)
    .join(" ");
}

function logError(req, context, error, extra = {}) {
  const requestId = req?.request_id || "unknown";
  const message = safeErrorMessage(error);
  const extraText = formatExtra(extra);
  const suffix = extraText ? ` ${extraText}` : "";
  console.error(`[${context}] request_id=${requestId} message=${message}${suffix}`);
}

module.exports = {
  logError,
};
