/**
 * @jest-environment node
 */

import request, { Header } from '../request'
import { http, HttpResponse } from 'msw'
import HttpStatus from 'http-status-codes'
import { server } from './msw/node'
import { exampleOrigin, exampleContent } from './msw/handlers'

describe('request (server, NodeJS https module)', () => {
  beforeAll(() => server.listen())
  afterEach(() => server.resetHandlers())
  afterAll(() => server.close())

  test('should make HEAD request', async () => {
    const resp = await request.head(exampleOrigin)

    expect(resp.status).toBe(HttpStatus.OK)
    expect(resp.headers.get(Header.ContentLength)).toBe(`${exampleContent.length}`)
    const data = await resp.text()
    expect(data).toBe('')
  })

  test('should make GET request', async () => {
    const resp = await request.get(exampleOrigin)

    expect(resp.status).toBe(HttpStatus.OK)
    expect(resp.headers.get(Header.ContentLength)).toBe(`${exampleContent.length}`)
    const data = await resp.text()
    expect(data).toBe(exampleContent)
  })

  test('should not throw error when status is not a success', async () => {
    server.use(http.get(exampleOrigin, () => new HttpResponse(null, { status: HttpStatus.BAD_REQUEST })))

    const resp = await request.get(exampleOrigin)

    expect(resp.status).toBe(HttpStatus.BAD_REQUEST)
  })

  test('should throw error when there is an error making the request', async () => {
    server.use(http.get(exampleOrigin, () => HttpResponse.error()))

    await expect(request.get(exampleOrigin)).rejects.toBeInstanceOf(Error)
  })
})
