import { Headers } from '../../../lib/headers/Headers.js'
import { HttpRequest } from '../../../models/HttpRequest.js'
import { IRequestAuthorization } from '../../../models/RequestAuthorization.js'

export interface MessagePreparationContext {
  request: HttpRequest
  hasProxy: boolean
  isProxyTunnel: boolean
  hostHeader?: string
  defaultHeaders?: boolean
  defaultUserAgent?: string
  defaultAccept?: string
  proxyUsername?: string
  proxyPassword?: string
  proxyAuthorization?: string
  authorization?: IRequestAuthorization[]
}

/**
 * Prepares headers list to be sent to the remote machine.
 * If `defaultHeaders` option is set then it adds `user-agent` and `accept`
 * headers.
 */
export function prepareHeaders(headers: Headers, context: MessagePreparationContext, withPayload = false): void {
  const { defaultHeaders, defaultUserAgent, defaultAccept, request } = context

  if (defaultHeaders) {
    if (!headers.has('user-agent')) {
      if (defaultUserAgent) {
        headers.set('user-agent', defaultUserAgent)
      } else {
        headers.set('user-agent', 'api client')
      }
    }
    if (!headers.has('accept')) {
      if (defaultAccept) {
        headers.set('accept', defaultAccept)
      } else {
        headers.set('accept', '*/*')
      }
    }
  }

  if (withPayload) {
    if (!headers.has('content-type') && request.payloadOptions) {
      if (request.payloadOptions.mime) {
        headers.set('content-type', request.payloadOptions.mime)
      }
    }
  }
}

/**
 * Generate proxy authorization header
 */
export function generateProxyAuthHeader(context: MessagePreparationContext): string | undefined {
  const { hasProxy, isProxyTunnel, proxyUsername, proxyPassword, proxyAuthorization } = context

  if (!hasProxy || isProxyTunnel) {
    return undefined
  }

  if (proxyAuthorization) {
    return proxyAuthorization
  }

  if (proxyUsername && proxyPassword) {
    const auth = `${proxyUsername}:${proxyPassword}`
    return `Basic ${Buffer.from(auth).toString('base64')}`
  }

  return undefined
}
