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

export const runtime = "nodejs"

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

    if (!file) {
      return NextResponse.json({ error: "Aucun fichier fourni" }, { status: 400 })
    }

    const allowedExtensions = [".jpg", ".jpeg", ".png", ".webp"]
    const hasValidExtension = allowedExtensions.some((ext) => file.name.toLowerCase().endsWith(ext))

    if (!hasValidExtension) {
      return NextResponse.json({ error: "Format non supporté. Utilisez JPG, PNG ou WebP." }, { status: 400 })
    }

    const provider = await getStorageProvider()

    if (provider === "vercel-blob" && file.size > 50 * 1024 * 1024) {
      return NextResponse.json({ error: "Fichier trop volumineux pour Vercel Blob. Maximum 50MB." }, { status: 400 })
    }

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

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

    let contentType = "image/jpeg"
    if (extension === "png") contentType = "image/png"
    else if (extension === "webp") contentType = "image/webp"

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

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

    return NextResponse.json({ url: result.url, provider: result.provider })
  } catch (error) {
    console.error("Image upload error:", error)
    return NextResponse.json({ error: "Erreur lors du téléchargement" }, { status: 500 })
  }
}
