import { type NextRequest, NextResponse } from "next/server"

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

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

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

    console.log("[v0] Audio compression request:", {
      filename: audioFile.name,
      originalSize: audioFile.size,
      type: audioFile.type,
    })

    // Target: 2.8MB max (~2940000 bytes)
    const TARGET_SIZE = 2940000 // 2.8MB
    const fileSizeInMB = audioFile.size / (1024 * 1024)

    // If file is already small enough, return it unchanged
    if (audioFile.size <= TARGET_SIZE) {
      console.log("[v0] File already under target size, skipping compression")
      const buffer = await audioFile.arrayBuffer()
      return new NextResponse(buffer, {
        status: 200,
        headers: {
          "Content-Type": audioFile.type || "audio/mpeg",
          "X-Original-Size": audioFile.size.toString(),
          "X-Compressed-Size": audioFile.size.toString(),
          "X-Compression-Ratio": "1.0",
        },
      })
    }

    // For files over target, we need aggressive compression
    // Use FFmpeg-like compression settings
    const targetBitrate = 64 // kbps - aggressive compression
    const targetSampleRate = 22050 // Hz - lower quality but smaller size

    console.log("[v0] Compressing audio with settings:", {
      targetBitrate,
      targetSampleRate,
      targetSize: TARGET_SIZE,
    })

    // Return the file with compression headers for client-side processing
    // Since we can't use FFmpeg in the browser, we'll use lamejs on the client
    const buffer = await audioFile.arrayBuffer()

    return new NextResponse(buffer, {
      status: 200,
      headers: {
        "Content-Type": audioFile.type || "audio/mpeg",
        "X-Original-Size": audioFile.size.toString(),
        "X-Requires-Compression": "true",
        "X-Target-Bitrate": targetBitrate.toString(),
        "X-Target-Sample-Rate": targetSampleRate.toString(),
      },
    })
  } catch (error) {
    console.error("[v0] Audio compression error:", error)
    return NextResponse.json({ error: "Compression failed" }, { status: 500 })
  }
}
