import defer from 'p-defer'
import type { Source, Duplex } from 'it-stream-types'

/**
 * A pair of streams where one drains from the other
 */
export function pair <T> (): Duplex<AsyncGenerator<T>, Source<T>, Promise<void>> {
  const deferred = defer<Source<T>>()
  let piped = false

  return {
    sink: async source => {
      if (piped) {
        throw new Error('already piped')
      }

      piped = true
      deferred.resolve(source)
    },
    source: (async function * () {
      const source = await deferred.promise

      yield * source
    }())
  }
}
