export const toApiData = <T>(valueArg: T): T => {
  if (Array.isArray(valueArg)) {
    return valueArg.map((itemArg) => toApiData(itemArg)) as T;
  }

  if (!valueArg || typeof valueArg !== 'object') {
    return valueArg;
  }

  const valueWithToData = valueArg as T & { toData?: () => unknown };
  if (typeof valueWithToData.toData === 'function') {
    return toApiData(valueWithToData.toData()) as T;
  }

  const prototype = Object.getPrototypeOf(valueArg);
  if (prototype !== Object.prototype && prototype !== null) {
    return valueArg;
  }

  return Object.fromEntries(
    Object.entries(valueArg as Record<string, unknown>).map(([keyArg, entryArg]) => [
      keyArg,
      toApiData(entryArg),
    ]),
  ) as T;
};

export const toApiDataArray = <T>(valuesArg: T[]): T[] => {
  return valuesArg.map((valueArg) => toApiData(valueArg));
};
