import { CID } from 'multiformats/cid';
import { multipartRequest } from 'ipfs-core-utils/multipart-request';
import { configure } from '../lib/configure.js';
import { toUrlSearchParams } from '../lib/to-url-search-params.js';
import { abortSignal } from '../lib/abort-signal.js';
export const createPut = configure(api => {
  async function put(data, options = {}) {
    const controller = new AbortController();
    const signal = abortSignal(controller.signal, options.signal);
    let res;
    try {
      const response = await api.post('block/put', {
        signal: signal,
        searchParams: toUrlSearchParams(options),
        ...await multipartRequest([data], controller, options.headers)
      });
      res = await response.json();
    } catch (err) {
      if (options.format === 'dag-pb') {
        return put(data, {
          ...options,
          format: 'protobuf'
        });
      } else if (options.format === 'dag-cbor') {
        return put(data, {
          ...options,
          format: 'cbor'
        });
      }
      throw err;
    }
    return CID.parse(res.Key);
  }
  return put;
});