import { test } from '@japa/runner'
import {
  CoreEngine,
  DummyLogger,
  HttpEngineOptions,
  IHttpRequest,
  INtlmAuthorization,
  IResponse,
  RequestAuthorizationKind,
  Headers,
} from '../../../../src/index.js'

const logger = new DummyLogger()

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 = log.response as IResponse
    assert.equal(response.status, 200, 'has the 200 status code')
  }).tags(['@http-engine', '@auth'])
})

test.group('_authorizeNtlm()', (group) => {
  let headers: Headers
  let engine: CoreEngine
  let request: IHttpRequest
  let opts: HttpEngineOptions
  let authConfig: INtlmAuthorization

  group.each.setup((ctx) => {
    headers = new Headers()
    request = {
      url: `http://localhost:${ctx.context.httpConfig.httpPort}/v1/get/`,
      method: 'GET',
      headers: 'Host: test.com',
    }
    authConfig = {
      domain: 'domain.com',
      username: 'test',
      password: 'test',
    }
    opts = {
      logger,
      authorization: [
        {
          kind: RequestAuthorizationKind,
          type: 'ntlm',
          enabled: true,
          valid: true,
          config: authConfig,
        },
      ],
    }
    engine = new CoreEngine(request, opts)
  })

  test('adds the authorization header', ({ assert }) => {
    engine._authorizeNtlm(authConfig, headers)
    assert.isTrue(headers.has('Authorization'))
  }).tags(['@http-engine', '@auth'])

  test('the authorization is NTLM', ({ assert }) => {
    engine._authorizeNtlm(authConfig as INtlmAuthorization, headers)
    const value = headers.get('Authorization') as string
    assert.equal(value.indexOf('NTLM '), 0)
  }).tags(['@http-engine', '@auth'])
})
