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

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

// Store chunks in memory temporarily (in production, use Redis or similar)
const uploadSessions = new Map<string, { chunks: Buffer[]; filename: string; contentType: string }>()

export async function POST(request: NextRequest) {
  try {
    const clientIp = request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip") || "anonymous"
    const rateLimitResult = await uploadRateLimit(clientIp)

    if (!rateLimitResult.allowed) {
      console.log(`[v0] [Upload Chunk] Rate limit exceeded for IP: ${clientIp}`)
      return NextResponse.json({ error: "Limite de téléchargement dépassée. Veuillez attendre." }, { status: 429 })
    }

    console.log("[v0] [Upload Chunk] ===== NEW CHUNK REQUEST =====")

    const formData = await request.formData()
    const sessionId = formData.get("sessionId") as string
    const chunkIndex = Number.parseInt(formData.get("chunkIndex") as string)
    const totalChunks = Number.parseInt(formData.get("totalChunks") as string)
    const filename = formData.get("filename") as string
    const contentType = formData.get("contentType") as string
    const chunk = formData.get("chunk") as Blob

    console.log(
      `[v0] [Upload Chunk] Received: sessionId=${sessionId}, chunk=${chunkIndex}/${totalChunks}, filename=${filename}`,
    )

    if (!sessionId || isNaN(chunkIndex) || isNaN(totalChunks) || !chunk) {
      console.error("[v0] [Upload Chunk] Missing required fields!")
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 })
    }

    console.log(
      `[v0] [Upload Chunk] Session ${sessionId}: chunk ${chunkIndex + 1}/${totalChunks}, size: ${chunk.size} bytes`,
    )

    // Initialize session if first chunk
    if (!uploadSessions.has(sessionId)) {
      console.log(`[v0] [Upload Chunk] Creating new session: ${sessionId}`)
      uploadSessions.set(sessionId, { chunks: [], filename, contentType })
    }

    const session = uploadSessions.get(sessionId)!

    // Store chunk
    const arrayBuffer = await chunk.arrayBuffer()
    session.chunks[chunkIndex] = Buffer.from(arrayBuffer)

    // Check if all chunks received
    const receivedChunks = session.chunks.filter(Boolean).length
    console.log(`[v0] [Upload Chunk] Progress: ${receivedChunks}/${totalChunks} chunks received`)

    if (receivedChunks === totalChunks) {
      console.log(`[v0] [Upload Chunk] ===== ALL CHUNKS RECEIVED - ASSEMBLING FILE =====`)

      // Combine all chunks
      const completeBuffer = Buffer.concat(session.chunks)
      console.log(`[v0] [Upload Chunk] Complete file size: ${completeBuffer.length} bytes`)

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

      console.log(`[v0] [Upload Chunk] Final path: ${finalPath}`)
      console.log(`[v0] [Upload Chunk] ===== STARTING STORAGE UPLOAD =====`)

      const result = await uploadFile({
        filename: finalPath,
        file: completeBuffer,
        contentType: session.contentType || "audio/mpeg",
        isAudio: true,
      })

      // Clean up session
      uploadSessions.delete(sessionId)

      console.log(`[v0] [Upload Chunk] ===== UPLOAD COMPLETE =====`)
      console.log(`[v0] [Upload Chunk] Provider: ${result.provider}`)
      console.log(`[v0] [Upload Chunk] URL: ${result.url}`)

      return NextResponse.json({
        complete: true,
        url: result.url,
        size: completeBuffer.length,
        provider: result.provider,
      })
    }

    return NextResponse.json({
      complete: false,
      received: receivedChunks,
      total: totalChunks,
    })
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown error"
    console.error("[v0] [Upload Chunk] ===== ERROR =====")
    console.error("[v0] [Upload Chunk] Error:", message)
    console.error("[v0] [Upload Chunk] Stack:", error instanceof Error ? error.stack : "No stack trace")
    return NextResponse.json({ error: message }, { status: 500 })
  }
}
