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

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

  return {
    begin(): WorkspaceRefreshTicket {
      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 WorkspaceRefreshGate = ReturnType<typeof createWorkspaceRefreshGate>
