var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function (resolve) {
      resolve(value);
    });
  }

  return new (P || (P = Promise))(function (resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }

    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }

    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }

    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};

import { filterHeaders, http } from "../utils/http.js";
import { extractUploadHeaders } from "../utils/headers.js";
import { BeeError } from "../utils/error.js";
const feedEndpoint = 'feeds';
/**
 * Create an initial feed root manifest
 *
 * @param ky Ky instance
 * @param owner           Owner's ethereum address in hex
 * @param topic           Topic in hex
 * @param postageBatchId  Postage BatchId to be used to create the Feed Manifest
 * @param options         Additional options, like type (default: 'sequence')
 */

export function createFeedManifest(ky, owner, topic, postageBatchId, options) {
  return __awaiter(this, void 0, void 0, function* () {
    const response = yield http(ky, {
      method: 'post',
      responseType: 'json',
      path: `${feedEndpoint}/${owner}/${topic}`,
      searchParams: filterHeaders(options),
      headers: extractUploadHeaders(postageBatchId)
    });
    return response.data.reference;
  });
}

function readFeedUpdateHeaders(headers) {
  const feedIndex = headers.get('swarm-feed-index');
  const feedIndexNext = headers.get('swarm-feed-index-next');

  if (!feedIndex) {
    throw new BeeError('Response did not contain expected swarm-feed-index!');
  }

  if (!feedIndexNext) {
    throw new BeeError('Response did not contain expected swarm-feed-index-next!');
  }

  return {
    feedIndex,
    feedIndexNext
  };
}
/**
 * Find and retrieve feed update
 *
 * The feed consists of updates. This endpoint looks up an
 * update that matches the provided parameters and returns
 * the reference it contains along with its index and the
 * index of the subsequent update.
 *
 * @param ky Ky instance
 * @param owner       Owner's ethereum address in hex
 * @param topic       Topic in hex
 * @param options     Additional options, like index, at, type
 */


export function fetchLatestFeedUpdate(ky, owner, topic, options) {
  return __awaiter(this, void 0, void 0, function* () {
    const response = yield http(ky, {
      responseType: 'json',
      path: `${feedEndpoint}/${owner}/${topic}`,
      searchParams: filterHeaders(options)
    });
    return Object.assign(Object.assign({}, response.data), readFeedUpdateHeaders(response.headers));
  });
}