function resolveUploadUrl(uploadUrl: string) {
  const trimmedUploadUrl = uploadUrl.trim()

  if (/^https?:\/\//i.test(trimmedUploadUrl)) {
    const url = new URL(trimmedUploadUrl)

    return `${url.pathname}${url.search}`
  }

  return trimmedUploadUrl
}

export async function uploadMultipartFile(
  uploadUrl: string,
  fieldName: string,
  file: File,
) {
  const formData = new FormData()

  formData.append(fieldName, file)

  const response = await fetch(resolveUploadUrl(uploadUrl), {
    method: 'POST',
    body: formData,
    credentials: 'include',
  })

  if (!response.ok) {
    const text = await response.text().catch(() => '')

    throw new Error(
      `Не удалось загрузить файл: ${response.status} ${text}`,
    )
  }
}