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

const logger = createLogger()

test.group('NTLM authorization', () => {
  test('returns 401 when no credentials', async ({ assert, httpConfig }) => {
    const engine = new CoreEngine(
      {
        url: `http://localhost:${httpConfig.httpPort}/v1/auth/ntlm/resource`,
        method: 'GET',
      },
      { logger }
    )
    const log = await engine.send()
    const response = log.response as IResponse
    assert.equal(response.status, 401, 'has the 401 status code')
  }).tags(['@http-engine', '@auth'])

  test('authenticates the user', async ({ assert, httpConfig }) => {
    const engine = new CoreEngine(
      {
        url: `http://localhost:${httpConfig.httpPort}/v1/auth/ntlm/resource`,
        method: 'GET',
      },
      {
        logger,
        authorization: [
          {
            kind: RequestAuthorizationKind,
            enabled: true,
            type: 'ntlm',
            valid: true,
            config: {
              username: 'u1',
              password: 'u2',
              domain: 'custom.com',
            },
          },
        ],
      }
    )
    const log = await engine.send()
    const response = new Response(log.response as IResponse)
    assert.equal(response.status, 200, 'has the 200 status code')
    const body = await response.readPayloadAsString()
    assert.ok(body, 'has the body')
    const rsp = JSON.parse(body as string)
    assert.deepEqual(rsp, { authenticated: true }, 'has the authenticated response')
  }).tags(['@http-engine', '@auth'])
})
