import { NextResponse } from "next/server"
import { sql } from "@/lib/db"

export async function POST() {
  try {
    // Get all tracks with audio URLs but zero duration
    const tracks = await sql`
      SELECT id, audio_url 
      FROM tracks 
      WHERE audio_url IS NOT NULL 
      AND duration_ms = 0
    `

    const results = []

    // Calculate duration for each track
    for (const track of tracks) {
      try {
        // Fetch the audio file to get its duration
        const response = await fetch(track.audio_url)
        const blob = await response.blob()

        // Create audio element to get duration
        const audioUrl = URL.createObjectURL(blob)
        const audio = new Audio(audioUrl)

        await new Promise((resolve, reject) => {
          audio.addEventListener("loadedmetadata", resolve)
          audio.addEventListener("error", reject)
          audio.load()
        })

        const durationMs = Math.floor(audio.duration * 1000)

        // Update the track duration
        await sql`
          UPDATE tracks 
          SET duration_ms = ${durationMs}
          WHERE id = ${track.id}
        `

        results.push({ id: track.id, duration_ms: durationMs, success: true })

        URL.revokeObjectURL(audioUrl)
      } catch (error) {
        results.push({ id: track.id, success: false, error: "Failed to calculate duration" })
      }
    }

    return NextResponse.json({
      success: true,
      message: `Recalculated durations for ${results.filter((r) => r.success).length} tracks`,
      results,
    })
  } catch (error) {
    console.error("Failed to recalculate durations:", error)
    return NextResponse.json({ error: "Failed to recalculate durations" }, { status: 500 })
  }
}
