import FileSaver from 'file-saver'
import { useAp2iRequestService } from '~/composables/data/useAp2iRequestService'
import File from '~/models/Core/File'

export const useDownloadFile = async (file: File) => {
  const { apiRequestService } = useAp2iRequestService()

  const downloadUrl = `api/download/${file.id}`

  const response = await apiRequestService.get(downloadUrl)

  const blobPart = await response.blob()

  if (!response || blobPart.size === 0) {
    console.error('Error: file ' + file.id + ' not found')
  }

  const blob = new Blob([blobPart], { type: response.type })

  // eslint-disable-next-line import/no-named-as-default-member
  FileSaver.saveAs(blob, file.name ?? 'unknown')
}
