import { test } from '@japa/runner'
import sinon from 'sinon'
import { createLogger, CoreEngine, IHttpRequest, HttpEngineOptions } from '../../../../src/index.js'

const logger = createLogger()

test.group('Events', (group) => {
  let engine: CoreEngine
  group.each.setup((ctx) => {
    const request: IHttpRequest = {
      url: `http://localhost:${ctx.context.httpConfig.httpPort}/v1/get/`,
      method: 'GET',
      headers: 'Host: test.com\nContent-Length: 0',
      payload: 'abc',
    }
    const opts: HttpEngineOptions = {
      logger,
    }
    engine = new CoreEngine(request, opts)
  })

  test('dispatches the "loadstart" event', async ({ assert }) => {
    const spy = sinon.spy()
    engine.once('loadstart', spy)
    await engine.send()
    assert.isTrue(spy.calledOnce)
  })

  test('dispatches the "firstbyte" event', async ({ assert }) => {
    const spy = sinon.spy()
    engine.once('firstbyte', spy)
    await engine.send()
    assert.isTrue(spy.calledOnce)
  })

  test('dispatches the "loadend" event', async ({ assert }) => {
    const spy = sinon.spy()
    engine.once('loadend', spy)
    await engine.send()
    assert.isTrue(spy.calledOnce)
  })

  test('dispatches the "headersreceived" event', async ({ assert }) => {
    const spy = sinon.spy()
    engine.once('headersreceived', spy)
    await engine.send()
    assert.isTrue(spy.calledOnce)
  })
})
