const csrfFetch = async (...params: Parameters<typeof fetch>) => {
  // fetch cookie from document.cookie
  const cookie = document.cookie
    .split(';')
    .map(c => c.trim())
    .find(c => c.startsWith('csrftoken='))
  const csrfToken = cookie?.split('=')[1]
  if (!csrfToken) {
    throw new Error('CSRF token not found')
  }

  // add csrf token to headers
  const [url, _options] = params
  const options = _options || {}
  if (!(options?.headers instanceof Headers)) {
    options.headers = new Headers(options?.headers)
  }
  if (!options.credentials) {
    options.credentials = 'include'
  }
  options.headers.set('X-CSRFToken', csrfToken)

  // make request
  return fetch(url, options)
}

export default csrfFetch
