/**
 * WHMCS PHP Serialization Utilities (domain-internal)
 */

import { byteLengthUtf8, utf8ToBase64 } from "./encoding.js";

/**
 * Serialize a key/value map into the format WHMCS expects for request parameters like `customfields`.
 *
 * Official docs:
 * - AddClient: customfields = "Base64 encoded serialized array of custom field values."
 *   @see https://developers.whmcs.com/api-reference/addclient/
 */
export function serializeWhmcsKeyValueMap(data?: Record<string, string>): string {
  if (!data) return "";
  const entries = Object.entries(data).filter(([k]) => String(k).trim().length > 0);
  if (entries.length === 0) return "";

  const serializedEntries = entries.map(([key, value]) => {
    const safeKey = key ?? "";
    const safeValue = value ?? "";
    return (
      `s:${byteLengthUtf8(safeKey)}:"${escapePhpString(safeKey)}";` +
      `s:${byteLengthUtf8(safeValue)}:"${escapePhpString(safeValue)}";`
    );
  });

  const serialized = `a:${serializedEntries.length}:{${serializedEntries.join("")}}`;
  return utf8ToBase64(serialized);
}

function escapePhpString(value: string): string {
  return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
}
