export function toFormData(
  value: unknown,
  form = new FormData(),
  parentKey?: string
) {
  if (value === undefined || value === null) {
    if (parentKey) form.append(parentKey, '');
    return form;
  }

  if (value instanceof File) {
    if (!parentKey) throw new Error('File must have a key');
    form.append(parentKey, value);
    return form;
  }

  if (Array.isArray(value)) {
    value.forEach((v, i) => {
      const key = parentKey ? `${parentKey}[${i}]` : `${i}`;
      toFormData(v, form, key);
    });
    return form;
  }

  if (typeof value === 'object') {
    Object.entries(value as Record<string, unknown>).forEach(([k, v]) => {
      const key = parentKey ? `${parentKey}[${k}]` : k;
      toFormData(v, form, key);
    });
    return form;
  }

  if (parentKey) form.append(parentKey, String(value));
  return form;
}

export function containsFile(obj: unknown): boolean {
  if (!obj) return false;
  if (obj instanceof File) return true;
  if (Array.isArray(obj)) return obj.some(containsFile);
  if (typeof obj === 'object') {
    return Object.values(obj as Record<string, unknown>).some(containsFile);
  }
  return false;
}
