import type { AxiosRequestConfig } from 'axios'
import http from './http'

function responseFileName(header: string | undefined, fallback: string) {
  if (!header) return fallback
  const encoded = header.match(/filename\*=UTF-8''([^;]+)/i)?.[1]
  if (encoded) return decodeURIComponent(encoded)
  const plain = header.match(/filename="?([^";]+)"?/i)?.[1]
  return plain || fallback
}

export async function downloadApiFile(
  path: string,
  fallbackName: string,
  config?: AxiosRequestConfig,
) {
  const response = await http.get(path, {
    ...config,
    responseType: 'blob',
  })
  const url = URL.createObjectURL(response.data)
  const anchor = document.createElement('a')
  anchor.href = url
  anchor.download = responseFileName(response.headers['content-disposition'], fallbackName)
  document.body.appendChild(anchor)
  anchor.click()
  anchor.remove()
  URL.revokeObjectURL(url)
}

export async function downloadApiPostFile(
  path: string,
  payload: unknown,
  fallbackName: string,
) {
  const response = await http.post(path, payload, { responseType: 'blob' })
  const url = URL.createObjectURL(response.data)
  const anchor = document.createElement('a')
  anchor.href = url
  anchor.download = responseFileName(response.headers['content-disposition'], fallbackName)
  document.body.appendChild(anchor)
  anchor.click()
  anchor.remove()
  URL.revokeObjectURL(url)
}

export async function importExcel(path: string, file: File) {
  const form = new FormData()
  form.append('file', file)
  return http.post(path, form, {
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 60000,
  })
}
