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

export const callApiBase = ({
  abortSignal,
  config,
  url,
}: CallApiArgs) => {
  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)
}

const callApiWithTimeout = (args: CallApiArgs) => {
  const { abortSignal, timeout } = args
  const abortController = new AbortController()
  const timeoutId = setTimeout(
    () => abortController.abort(),
    timeout,
  )

  if (abortSignal) {
    abortSignal.addEventListener('abort', () => abortController.abort())
  }

  return callApiBase({
    ...args,
    abortSignal: abortSignal || abortController.signal,
  })
    .then(checkStatus)
    .then(parseJSON)
    .catch(logoutIfUnauthorized)
    .finally(() => clearTimeout(timeoutId))
}

export const callApi = (args: CallApiArgs) => {
  if (args.timeout) return callApiWithTimeout(args)

  return callApiBase(args)
    .then(checkStatus)
    .then(parseJSON)
    .catch(logoutIfUnauthorized)
}
