function createCommentNext({ post, queue, queueKind = '', canQueue, accept = () => undefined, complete }) {
  let inFlight = null;

  async function admitQueued(item, message) {
    const admission = await queue(message);
    if (!admission || (!admission.item && admission.durable !== true)) {
      throw new Error('Comment was not saved for delivery.');
    }
    accept(item, { delivery: admission.background ? 'queued' : 'saved' });
    return {
      accepted: true,
      delivery: admission.background ? 'queued' : 'saved',
      background: Boolean(admission.background),
      completed: Boolean(complete(item)),
    };
  }

  function submit(item, body, operationId = '') {
    if (inFlight) return inFlight;
    inFlight = (async () => {
      try {
        let comment;
        try {
          comment = await post(item, body, typeof operationId === 'function' ? operationId() : operationId);
        } catch (error) {
          if (!canQueue(error)) throw error;
          const identity = queueKind === 'update-reply' ? {
            kind: 'update-reply', notificationId: item.notification_id,
          } : {
            kind: item.kind === 'pull' ? 'pull-comment' : 'issue-comment',
            repository: item.repository, number: item.number,
          };
          return admitQueued(item, {
            ...identity, body,
            operationId: typeof operationId === 'function' ? operationId() : operationId,
          });
        }
        accept(item, { delivery: 'posted', comment });
        return {
          accepted: true,
          delivery: 'posted',
          comment,
          completed: Boolean(complete(item)),
        };
      } finally {
        inFlight = null;
      }
    })();
    return inFlight;
  }

  function admit(item, message) {
    if (inFlight) return inFlight;
    inFlight = admitQueued(item, message).finally(() => { inFlight = null; });
    return inFlight;
  }

  return { submit, admit, busy: () => Boolean(inFlight) };
}

if (typeof module !== 'undefined' && module.exports) module.exports = createCommentNext;
