import { type NextRequest, NextResponse } from "next/server"
import { handleUpload, type HandleUploadBody } from "@vercel/blob/client"

export const runtime = "nodejs"
export const maxDuration = 60

export async function POST(request: NextRequest) {
  const token = process.env.BLOB_READ_WRITE_TOKEN

  if (!token) {
    console.error("[Upload Token] BLOB_READ_WRITE_TOKEN not configured")
    return NextResponse.json({ error: "Storage not configured" }, { status: 500 })
  }

  try {
    // Parse the request body for handleUpload
    const body = (await request.json()) as HandleUploadBody

    console.log("[Upload Token] Processing request type:", body.type)

    const jsonResponse = await handleUpload({
      body,
      request,
      token, // Explicitly pass the token
      onBeforeGenerateToken: async (pathname) => {
        // Generate unique path for audio files
        const timestamp = Date.now()
        const randomStr = Math.random().toString(36).substring(2, 15)
        const extension = pathname.split(".").pop()?.toLowerCase() || "mp3"
        const finalPath = `audio/${timestamp}-${randomStr}.${extension}`

        console.log("[Upload Token] Generating token for:", finalPath)

        return {
          allowedContentTypes: [
            "audio/mpeg",
            "audio/mp3",
            "audio/flac",
            "audio/wav",
            "audio/aac",
            "audio/ogg",
            "audio/mp4",
            "audio/x-m4a",
          ],
          maximumSizeInBytes: 500 * 1024 * 1024, // 500MB
          validUntil: Date.now() + 60 * 60 * 1000, // 1 hour
          addRandomSuffix: false,
          pathname: finalPath,
        }
      },
      onUploadCompleted: async ({ blob }) => {
        console.log("[Upload Token] Upload completed:", blob.url)
      },
    })

    return NextResponse.json(jsonResponse)
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown error"
    console.error("[Upload Token] Error:", message)
    return NextResponse.json({ error: message }, { status: 500 })
  }
}
