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

export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData()
    const file = formData.get("file") as File

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

    const provider = await getStorageProvider()

    // Cloudflare R2 has no file size limit, Vercel Blob has serverless limits
    const serverlessLimit = 4.5 * 1024 * 1024
    if (provider === "vercel-blob" && file.size > serverlessLimit) {
      return NextResponse.json(
        {
          error: `Fichier trop volumineux pour Vercel Blob (${(file.size / 1024 / 1024).toFixed(1)}MB). Maximum 4.5MB pour l'upload serveur avec Vercel Blob. Basculez vers Cloudflare R2 pour les fichiers plus volumineux.`,
        },
        { status: 413 },
      )
    }

    console.log(`[Upload] Storage provider: ${provider}, File size: ${(file.size / 1024 / 1024).toFixed(2)}MB`)

    const allowedAudioTypes = [
      "audio/mpeg",
      "audio/mp3",
      "audio/wav",
      "audio/flac",
      "audio/aac",
      "audio/ogg",
      "audio/x-m4a",
    ]
    const allowedImageTypes = ["image/jpeg", "image/png", "image/webp", "image/gif"]
    const isAudio = allowedAudioTypes.includes(file.type)
    const isImage = allowedImageTypes.includes(file.type)

    if (!isAudio && !isImage) {
      return NextResponse.json({ error: "Invalid file type" }, { status: 400 })
    }

    // Use storage provider abstraction
    const timestamp = Date.now()
    const randomStr = Math.random().toString(36).substring(2, 15)
    const extension = file.name.split(".").pop() || (isAudio ? "mp3" : "jpg")
    const folder = isAudio ? "audio" : "images"
    const filename = `${folder}/${timestamp}-${randomStr}.${extension}`

    const result = await uploadFile({
      filename,
      file,
      folder,
      contentType: file.type,
    })

    return NextResponse.json({
      url: result.url,
      filename: file.name,
      size: file.size,
      type: file.type,
      provider: result.provider,
    })
  } catch (error) {
    console.error("Upload API error:", error)
    return NextResponse.json({ error: error instanceof Error ? error.message : "Upload failed" }, { status: 500 })
  }
}
