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

const logger = createLogger()

test.group('Timeout test', (group) => {
  let opts: HttpEngineOptions

  group.each.setup(() => {
    opts = {
      timeout: 60,
      followRedirects: false,
      logger,
    }
  })

  test('timeouts the request', async ({ assert, httpConfig }) => {
    const request: IHttpRequest = {
      url: `http://localhost:${httpConfig.httpPort}/v1/delay/1000`,
      method: 'GET',
    }
    const engine = new CoreEngine(request, opts)
    const spy = sinon.spy()
    engine.on('loadend', spy)
    const info = await engine.send()
    assert.isFalse(spy.called, 'loadend was not called')
    const response = info.response as IErrorResponse
    assert.equal(response.status, 0, 'status is 0')
    assert.equal((response.error as ISerializedError).message, 'Connection timeout after 60ms')
  })
})
