function createSearchDefer({ claim, accept, defer, refresh, announce, formatTime }) {
  let request = null;

  function run(detail, until) {
    if (request) return request;
    const wasClaimable = Boolean(detail?.claimable);
    request = Promise.resolve(wasClaimable ? claim(detail) : detail)
      .then(confirmed => {
        const item = accept(confirmed);
        const outcome = defer(item, until);
        refresh();
        if (outcome === 'deferred') {
          announce((wasClaimable ? 'Assigned and deferred until ' : 'Deferred until ') + formatTime(until) + '.');
        } else {
          announce(wasClaimable
            ? 'Assignment succeeded, but Later could not be saved. Open this issue in My Work to retry.'
            : 'Could not save Later on this device. Retry scheduling.');
        }
        return outcome;
      })
      .finally(() => { request = null; });
    return request;
  }

  return { run, pending:() => Boolean(request) };
}

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