/**
 * Minimal helpers for building the small, numeric-only XML fragments the
 * Auslieferung.sp* procedures expect (see delivery.md §3 for the exact
 * schemas). SQL Server's `xml` type happily holds multiple top-level
 * elements, so a "fragment" here is just concatenated <Tag>...</Tag> blocks.
 */

function escapeXml(value) {
  return String(value).replace(/[<>&'"]/g, (c) => {
    switch (c) {
      case '<':
        return '&lt;';
      case '>':
        return '&gt;';
      case '&':
        return '&amp;';
      case "'":
        return '&apos;';
      case '"':
        return '&quot;';
      default:
        return c;
    }
  });
}

/** Builds `<tag>value</tag>`, or `<tag/>` when value is null/undefined. */
export function xmlTag(tag, value) {
  if (value == null) {
    return `<${tag}/>`;
  }
  return `<${tag}>${escapeXml(value)}</${tag}>`;
}

/** Wraps a set of child tags (already-built strings) in `<tag>...</tag>`. */
export function xmlElement(tag, childrenXml) {
  return `<${tag}>${childrenXml.join('')}</${tag}>`;
}
