import { TOKEN_KEY } from 'config'
import { readToken } from 'helpers'

import type { RequestConfig } from './types'

export const getRequestConfig = (
  config: RequestConfig,
  signal?: AbortSignal,
) => {
  const requestConfig = {
    ...config,
    headers: config.headers || new Headers(),
    method: config.method || 'POST',
    signal,
  }

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

  const token = readToken()

  if (token) {
    requestConfig.headers.set(TOKEN_KEY, `Bearer ${token}`)
  }

  return requestConfig
}
