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 corsHeaders = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "POST, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type",
  }

  try {
    console.log("[Multipart Upload] === REQUEST RECEIVED ===")

    const formData = await request.formData()
    const file = formData.get("file") as File
    const filename = formData.get("filename") as string

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

    const fileSizeMB = file.size / (1024 * 1024)
    console.log(`[Multipart Upload] File: ${file.name}, Size: ${fileSizeMB.toFixed(2)}MB`)

    // Validate file extension
    const allowedExtensions = [".mp3", ".flac", ".wav", ".aac", ".ogg", ".m4a"]
    const hasValidExtension = allowedExtensions.some((ext) => (filename || file.name).toLowerCase().endsWith(ext))

    if (!hasValidExtension) {
      return NextResponse.json(
        { error: "Format audio non supporté. Utilisez MP3, FLAC, WAV, AAC, OGG ou M4A." },
        { status: 400, headers: corsHeaders },
      )
    }

    // Determine content type
    const extension = (filename || file.name).split(".").pop()?.toLowerCase() || "mp3"
    let contentType = "audio/mpeg"
    if (extension === "flac") contentType = "audio/flac"
    else if (extension === "wav") contentType = "audio/wav"
    else if (extension === "aac") contentType = "audio/aac"
    else if (extension === "ogg") contentType = "audio/ogg"
    else if (extension === "m4a") contentType = "audio/mp4"

    const finalFilename = filename || `audio/${Date.now()}-${Math.random().toString(36).substring(2, 15)}.${extension}`

    console.log(`[Multipart Upload] Uploading to Vercel Blob: ${finalFilename}`)

    // Use Vercel Blob with multipart option for large files
    const blob = await put(finalFilename, file, {
      access: "public",
      contentType,
      multipart: true,
    })

    console.log("[Multipart Upload] Success:", blob.url)

    return NextResponse.json({ url: blob.url, provider: "vercel-blob" }, { headers: corsHeaders })
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error)
    console.error("[Multipart Upload] Error:", errorMessage)
    return NextResponse.json({ error: `Upload failed: ${errorMessage}` }, { status: 500, headers: corsHeaders })
  }
}

export async function OPTIONS() {
  return new NextResponse(null, {
    status: 200,
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "POST, OPTIONS",
      "Access-Control-Allow-Headers": "Content-Type",
    },
  })
}
