import { type NextRequest, NextResponse } from "next/server"
import { put } from "@vercel/blob"

export const runtime = "nodejs"
export const maxDuration = 300

export async function POST(request: NextRequest) {
  const token = process.env.BLOB_READ_WRITE_TOKEN
  if (!token) {
    return NextResponse.json({ error: "Storage not configured" }, { status: 500 })
  }

  try {
    const formData = await request.formData()
    const file = formData.get("file") as File | null
    const pathFromClient = formData.get("path") as string | null

    if (!file) {
      return NextResponse.json({ error: "No file provided" }, { status: 400 })
    }

    // Generate path if not provided
    const timestamp = Date.now()
    const randomStr = Math.random().toString(36).substring(2, 15)
    const extension = file.name.split(".").pop()?.toLowerCase() || "mp3"
    const blobPath = pathFromClient || `audio/${timestamp}-${randomStr}.${extension}`

    console.log("[Upload Direct] Starting upload:", blobPath, "Size:", file.size)

    // Use server-side put() with multipart for large files
    const blob = await put(blobPath, file, {
      access: "public",
      token,
      multipart: true,
      contentType: file.type || "audio/mpeg",
    })

    console.log("[Upload Direct] Complete:", blob.url)

    return NextResponse.json({
      success: true,
      url: blob.url,
    })
  } catch (error) {
    const message = error instanceof Error ? error.message : "Upload failed"
    console.error("[Upload Direct] Error:", message)
    return NextResponse.json({ error: message }, { status: 500 })
  }
}
