import { TCallApi } from './types'
import { parseJSON } from './parseJSON'
import { checkStatus } from './checkStatus'
import { getRequestConfig } from './getRequestConfig'
import { logoutIfUnauthorized } from './logoutIfUnauthorized'

export const callApiBase = ({
  abortSignal,
  config,
  url,
}: TCallApi) => {
  const requestConfig = getRequestConfig(config, abortSignal)

  // eslint-disable-next-line no-console
  console.log(
    '%c callApi from module - config ',
    'color: white; background-color: #95B46A',
    config,
  )

  return fetch(url, requestConfig)
}

export const callApi = ({
  abortSignal,
  config,
  url,
}: TCallApi) => (
  callApiBase({
    abortSignal,
    config,
    url,
  }).then(checkStatus)
    .then(parseJSON)
    .catch(logoutIfUnauthorized)
)
