import { download, post } from '@/lib/http/client'
import type {
  ExportUsersParams,
  ImportExportFormat,
  ImportUsersResult,
} from '@/types/import-export'

const API_BASE = '/admin/users'

function triggerFileDownload(blob: Blob, filename: string) {
  const link = document.createElement('a')
  const objectUrl = window.URL.createObjectURL(blob)
  link.href = objectUrl
  link.setAttribute('download', filename)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(objectUrl)
}

export async function exportUsers(params: ExportUsersParams): Promise<void> {
  const blob = await download(`${API_BASE}/export`, {
    format: params.format,
    fields: params.fields.join(','),
    keyword: params.keyword,
    status: params.status,
  })

  triggerFileDownload(
    blob,
    `users_${new Date().toISOString().slice(0, 10)}.${params.format}`,
  )
}

export async function downloadImportTemplate(
  format: ImportExportFormat,
): Promise<void> {
  const blob = await download(`${API_BASE}/import/template`, { format })
  triggerFileDownload(blob, `users_import_template.${format}`)
}

export function importUsers(file: File): Promise<ImportUsersResult> {
  const formData = new FormData()
  formData.append('file', file)

  return post<ImportUsersResult>(`${API_BASE}/import`, formData)
}
