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

const logger = createLogger()

test.group('POST requests', (group) => {
  let request: IHttpRequest
  let opts: HttpEngineOptions

  group.each.setup((ctx) => {
    request = {
      url: `http://localhost:${ctx.context.httpConfig.httpPort}/v1/tests/`,
      method: 'POST',
      headers: 'Host: test.com\nContent-Length: 0',
      payload: 'abc',
    }
    opts = {
      timeout: 50000,
      followRedirects: false,
      logger,
    }
  })

  test('makes a POST request', async ({ assert }) => {
    const engine = new CoreEngine(request, opts)
    const log = await engine.send()
    assert.ok(log)
  })

  test('response has stats', async ({ assert }) => {
    const engine = new CoreEngine(request, opts)
    const log = await engine.send()
    const response = new Response(log.response as IResponse)
    assert.equal(response.status, 200)
  })

  test('response has statusText', async ({ assert }) => {
    const engine = new CoreEngine(request, opts)
    const log = await engine.send()
    const response = new Response(log.response as IResponse)
    assert.equal(response.statusText, 'OK')
  })

  test('response has headers', async ({ assert }) => {
    const engine = new CoreEngine(request, opts)
    const log = await engine.send()
    const response = new Response(log.response as IResponse)
    assert.typeOf(response.headers, 'string')
  })

  test('has response payload', async ({ assert }) => {
    const engine = new CoreEngine(request, opts)
    const log = await engine.send()
    const response = new Response(log.response as IResponse)
    assert.ok(response.payload)
  })

  test('has the response timings object', async ({ assert }) => {
    const engine = new CoreEngine(request, opts)
    const log = await engine.send()
    const response = new Response(log.response as IResponse)
    assert.typeOf(response.timings, 'object')
  })

  test('has response sentHttpMessage', async ({ assert }) => {
    const engine = new CoreEngine(request, opts)
    const log = await engine.send()
    const sent = log.request as ISentRequest
    assert.typeOf(sent.httpMessage, 'string')
  })
})
