import { adminApi } from './client'
import { unwrapItem } from './helpers'

type UploadResponse = {
  data?: {
    path?: string
    url?: string
  }
}

export async function uploadImage(file: File) {
  const formData = new FormData()
  formData.append('file', file)

  const response = await adminApi.post<UploadResponse>('/uploads', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })

  const data = unwrapItem(response)
  return {
    path: (data.path as string) ?? '',
    url: (data.url as string) ?? '',
  }
}

export async function uploadVideo(file: File, onProgress?: (percent: number) => void) {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('type', 'video')

  const response = await adminApi.post<UploadResponse>('/uploads', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    timeout: 300000,
    onUploadProgress: onProgress
      ? (event) => {
          const percent = event.total ? Math.round((event.loaded * 100) / event.total) : 0
          onProgress(percent)
        }
      : undefined,
  })

  const data = unwrapItem(response)
  return {
    path: (data.path as string) ?? '',
    url: (data.url as string) ?? '',
  }
}
