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

export const callApi = ({
  abortController,
  config,
  url,
}: TCallApi) => {
  const requestConfig = getRequestConfig(config, abortController)

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

  return fetch(url, requestConfig)
    .then(checkStatus)
    .then(parseJSON)
    .catch((error) => {
      if (error.message === 'Unauthorized') {
        clearUserAuthInfo()
        removeCookie('token')

        if (window.location.pathname !== '/login') {
          localStorage.setItem('backLocation', window.location.pathname)
          window.location.pathname = '/login'
        }
      }

      // eslint-disable-next-line no-console
      console.error(error)
      return Promise.reject(error)
    })
}

export { getResponseData } from './getResponseData'
