import { getCookieByName } from './cookies'

export const downloadPDF = (pdfUrl: string) => {
  if (typeof window === 'undefined') return

  const xtfCookie = getCookieByName('X-TF-ECOMMERCE')

  if (!xtfCookie) return

  let headers = {}

  if (xtfCookie) {
    headers = {
      'X-TF-ECOMMERCE': xtfCookie,
    }
  }

  return fetch(pdfUrl, {
    headers,
    credentials: 'include',
  })
    .then(async response => {
      const blobValue = await response.blob()
      const fileNameHeader = response.headers.get('content-disposition') || ''
      const fileName = fileNameHeader.split('"')[1]
      return { blobValue, fileName }
    })
    .then(({ blobValue, fileName }) => {
      if (!fileName) {
        throw Error('Something went wrong.')
      }
      const file = new Blob([blobValue], { type: 'application/pdf' })
      const fileURL = URL.createObjectURL(file)
      const link = document.createElement('a')
      link.href = fileURL
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    })
    .catch(error => error)
}
