export type SearchRequestTicket = {
  signal: AbortSignal
  isCurrent: () => boolean
}

export function createSearchRequestGate() {
  let generation = 0
  let controller: AbortController | null = null

  return {
    begin(): SearchRequestTicket {
      generation += 1
      controller?.abort()
      controller = new AbortController()
      const requestGeneration = generation
      return {
        signal: controller.signal,
        isCurrent: () => requestGeneration === generation,
      }
    },
    invalidate() {
      generation += 1
      controller?.abort()
      controller = null
    },
  }
}

export type SearchRequestGate = ReturnType<typeof createSearchRequestGate>
