import { type NextRequest, NextResponse } from "next/server"
import { uploadFile, getStorageProvider } from "@/lib/storage-provider"

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

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

export async function POST(request: NextRequest) {
  const corsHeaders = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type, Authorization",
  }

  try {
    // Handle traditional FormData uploads (for small files)
    console.log("[Upload Audio] === FORMDATA UPLOAD ===")
    const formData = await request.formData()

    const file = formData.get("file") as File
    const duration = formData.get("duration") as string

    if (!file) {
      console.log("[Upload Audio] No file provided")
      return NextResponse.json({ error: "Aucun fichier fourni" }, { status: 400, headers: corsHeaders })
    }

    console.log(`[Upload Audio] File received: ${file.name}, size: ${file.size} bytes, type: ${file.type}`)

    const allowedExtensions = [".mp3", ".flac", ".wav", ".aac", ".ogg", ".m4a"]
    const hasValidExtension = allowedExtensions.some((ext) => 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 },
      )
    }

    const provider = await getStorageProvider()
    const fileSizeMB = file.size / (1024 * 1024)

    console.log(`[Upload Audio] Storage provider: ${provider}, Size: ${fileSizeMB.toFixed(2)}MB`)

    // For Vercel Blob with files > 4.5MB, return instruction to use client upload
    if (provider === "vercel-blob" && file.size > 4.5 * 1024 * 1024) {
      return NextResponse.json(
        { error: "USE_CLIENT_UPLOAD", message: "File too large for server upload, use client-side multipart upload" },
        { status: 400, headers: corsHeaders },
      )
    }

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

    console.log(`[Upload Audio] Generated filename: ${filename}`)

    try {
      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"

      console.log(`[Upload Audio] Content-Type: ${contentType}`)

      const result = await uploadFile({
        filename,
        file,
        folder: "audio",
        contentType,
        isAudio: true,
      })

      console.log("[Upload Audio] File uploaded successfully:", result.url)

      return NextResponse.json(
        {
          url: result.url,
          duration: duration ? Number.parseInt(duration) : null,
          provider: result.provider,
        },
        { headers: corsHeaders },
      )
    } catch (uploadError) {
      const errorMessage = uploadError instanceof Error ? uploadError.message : String(uploadError)
      console.error("[Upload Audio] Storage upload error:", errorMessage)
      return NextResponse.json(
        { error: `Erreur lors de l'upload: ${errorMessage}` },
        { status: 500, headers: corsHeaders },
      )
    }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error)
    console.error("[Upload Audio] FATAL ERROR:", errorMessage)
    return NextResponse.json(
      { error: errorMessage || "Erreur lors du téléchargement" },
      { status: 500, headers: corsHeaders },
    )
  }
}
