// jQuery `$.param`-compatible deep serializer: some endpoints expect the exact
// bracketed form-encoding jQuery produced (`key[sub][]=v` for primitive arrays).
export const jqueryParam = (obj: unknown): string => {
  const pairs: string[] = [];
  const add = (key: string, value: unknown) => {
    const v = value == null ? '' : String(value);
    pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(v)}`);
  };
  const build = (prefix: string, value: unknown) => {
    if (Array.isArray(value)) {
      value.forEach(item => build(`${prefix}[]`, item));
    } else if (value !== null && typeof value === 'object') {
      Object.entries(value as Record<string, unknown>).forEach(([k, val]) => build(`${prefix}[${k}]`, val));
    } else {
      add(prefix, value);
    }
  };
  Object.entries(obj as Record<string, unknown>).forEach(([k, val]) => build(k, val));
  // jQuery encodes spaces as '+'.
  return pairs.join('&').replace(/%20/g, '+');
};
