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

export const runtime = "nodejs"

export async function POST(request: NextRequest) {
  try {
    const { filename, contentType, fileType } = await request.json()

    if (!filename || !contentType) {
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 })
    }

    if (!process.env.BLOB_READ_WRITE_TOKEN) {
      return NextResponse.json({ error: "Blob storage not configured" }, { status: 500 })
    }

    // Generate unique key
    const timestamp = Date.now()
    const randomStr = Math.random().toString(36).substring(2, 15)
    const extension = filename.split(".").pop()?.toLowerCase() || "mp3"
    const folder = fileType === "audio" ? "audio" : "covers"
    const key = `${folder}/${timestamp}-${randomStr}.${extension}`

    console.log(`[Presigned] For Vercel Blob, use direct upload instead: ${key}`)

    // Vercel Blob doesn't support presigned URLs in the same way
    // Return info to use direct upload instead
    return NextResponse.json({
      useDirectUpload: true,
      key,
      endpoint: "/api/upload/audio/direct",
    })
  } catch (error) {
    console.error("[Presigned] Error:", error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Failed to process request" },
      { status: 500 },
    )
  }
}
