import assert from 'node:assert/strict'
import test from 'node:test'
import { createSearchRequestGate } from '../src/app/search-request-gate.ts'

test('starting a new request aborts and invalidates the previous request', () => {
  const gate = createSearchRequestGate()
  const first = gate.begin()
  const second = gate.begin()

  assert.equal(first.signal.aborted, true)
  assert.equal(first.isCurrent(), false)
  assert.equal(second.signal.aborted, false)
  assert.equal(second.isCurrent(), true)
})

test('session cleanup aborts the request and suppresses its stale error', async () => {
  const gate = createSearchRequestGate()
  const request = gate.begin()
  const surfacedErrors = []
  const oldSessionFailure = Promise.reject(new Error('旧会话搜索失败')).catch((error) => {
    if (request.isCurrent()) surfacedErrors.push(error.message)
  })

  gate.invalidate()
  await oldSessionFailure

  assert.equal(request.signal.aborted, true)
  assert.equal(request.isCurrent(), false)
  assert.deepEqual(surfacedErrors, [])
})

test('a request after invalidation belongs to the new session generation', () => {
  const gate = createSearchRequestGate()
  const oldSessionRequest = gate.begin()
  gate.invalidate()
  const newSessionRequest = gate.begin()

  assert.equal(oldSessionRequest.isCurrent(), false)
  assert.equal(newSessionRequest.isCurrent(), true)
  assert.equal(newSessionRequest.signal.aborted, false)
})
