import { put as blobPut } from "@vercel/blob"

export type StorageProvider = "vercel-blob"

export interface UploadOptions {
  filename: string
  file: File | Blob | Buffer
  folder?: string
  contentType?: string
  isAudio?: boolean
  isImage?: boolean
}

export interface UploadResult {
  url: string
  provider: StorageProvider
  verified: boolean
}

export async function getStorageProvider(): Promise<StorageProvider> {
  return "vercel-blob"
}

async function uploadToVercelBlob(options: UploadOptions): Promise<string> {
  const { filename, file, contentType, isAudio } = options

  let buffer: Buffer
  if (Buffer.isBuffer(file)) {
    buffer = file
  } else {
    const arrayBuffer = await (file as Blob).arrayBuffer()
    buffer = Buffer.from(arrayBuffer)
  }

  // Determine content type
  let finalContentType = contentType || "application/octet-stream"
  
  if (isAudio || filename.includes("audio/")) {
    const ext = filename.split(".").pop()?.toLowerCase()
    if (ext === "mp3") finalContentType = "audio/mpeg"
    else if (ext === "wav") finalContentType = "audio/wav"
    else if (ext === "m4a") finalContentType = "audio/mp4"
    else if (ext === "ogg") finalContentType = "audio/ogg"
    else if (ext === "flac") finalContentType = "audio/flac"
    else finalContentType = "audio/mpeg"
  }

  console.log(`[Storage] Uploading to Vercel Blob: ${filename} (${finalContentType})`)

  const blob = await blobPut(filename, buffer, {
    access: "public",
    addRandomSuffix: false,
    contentType: finalContentType,
  })

  console.log(`[Storage] Upload complete: ${blob.url}`)

  return blob.url
}

export async function uploadFile(options: UploadOptions): Promise<UploadResult> {
  try {
    const fileSize = Buffer.isBuffer(options.file) ? options.file.length : (options.file as Blob).size

    if (fileSize === 0) {
      throw new Error("Cannot upload empty file")
    }

    if (!process.env.BLOB_READ_WRITE_TOKEN) {
      throw new Error("BLOB_READ_WRITE_TOKEN not configured")
    }

    const url = await uploadToVercelBlob(options)
    return { url, provider: "vercel-blob", verified: true }
  } catch (error: any) {
    console.error("[Storage] Upload error:", error.message)
    throw error
  }
}

export async function testStorageProvider(provider: StorageProvider): Promise<boolean> {
  return !!process.env.BLOB_READ_WRITE_TOKEN
}
