export async function uploadFileDirect(
  file: File,
  fileType: "audio" | "cover",
  onProgress?: (progress: number) => void,
): Promise<string> {
  try {
    console.log(`[Direct Upload] Starting upload: ${file.name}, size: ${file.size} bytes`)

    const formData = new FormData()
    formData.append("file", file)
    formData.append("fileType", fileType)

    const xhr = new XMLHttpRequest()

    return new Promise((resolve, reject) => {
      xhr.upload.addEventListener("progress", (e) => {
        if (e.lengthComputable && onProgress) {
          const progress = (e.loaded / e.total) * 100
          onProgress(progress)
        }
      })

      xhr.addEventListener("load", () => {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const response = JSON.parse(xhr.responseText)
            console.log(`[Direct Upload] Upload successful! URL: ${response.url}`)
            resolve(response.url)
          } catch {
            reject(new Error("Invalid response from server"))
          }
        } else {
          console.error(`[Direct Upload] Upload failed: ${xhr.status}`, xhr.responseText)
          reject(new Error(`Upload failed: ${xhr.status}`))
        }
      })

      xhr.addEventListener("error", () => {
        console.error("[Direct Upload] Network error")
        reject(new Error("Network error during upload"))
      })

      xhr.addEventListener("abort", () => {
        console.error("[Direct Upload] Upload aborted")
        reject(new Error("Upload aborted"))
      })

      xhr.open("POST", "/api/upload/audio/direct")
      xhr.send(formData)
    })
  } catch (error) {
    console.error("[Direct Upload] Error:", error)
    throw error
  }
}

// Keep old name for backward compatibility
export const uploadFileDirectToR2 = uploadFileDirect
