import isString from 'lodash/isString'

import { loadIdToken } from './loadIdToken'
import { TRequestAbortController, TRequestConfig } from './types'

export const getRequestConfig = (
  config: TRequestConfig,
  abortController?: TRequestAbortController,
) => {
  const requestConfig = {
    method: 'POST',
    ...config,
    headers: new Headers(),
  }

  if (config.body && !isString(config.body)) {
    requestConfig.body = JSON.stringify(config.body)
  }

  if (config.body) {
    requestConfig.headers.set('Content-Type', 'application/json')
  }

  if (abortController) {
    requestConfig.signal = abortController.signal
  }

  const token = loadIdToken()

  if (token) {
    requestConfig.headers.set('x-auth-token', token)
  }

  return requestConfig
}
