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

export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const { searchParams } = new URL(request.url)
    const quality = searchParams.get("quality") || "high"

    // Get track with audio URL
    const tracks = await sql`
      SELECT t.audio_url, t.audio_url_low, t.audio_url_normal, t.audio_url_high, t.title, a.name as artist_name
      FROM tracks t
      LEFT JOIN artists a ON t.artist_id = a.id
      WHERE t.id = ${id}
    `

    if (tracks.length === 0) {
      return NextResponse.json({ error: "Track not found" }, { status: 404 })
    }

    const track = tracks[0]

    let audioUrl = track.audio_url
    if (quality === "low" && track.audio_url_low) {
      audioUrl = track.audio_url_low
    } else if (quality === "normal" && track.audio_url_normal) {
      audioUrl = track.audio_url_normal
    } else if (quality === "high" && track.audio_url_high) {
      audioUrl = track.audio_url_high
    } else if (quality === "very_high" && track.audio_url) {
      audioUrl = track.audio_url
    }

    if (!audioUrl) {
      return NextResponse.json({ error: "No audio file available" }, { status: 404 })
    }

    const audioResponse = await fetch(audioUrl)

    if (!audioResponse.ok) {
      return NextResponse.json({ error: "Failed to fetch audio file" }, { status: 500 })
    }

    const audioBlob = await audioResponse.blob()

    // Return the audio file with proper headers
    return new NextResponse(audioBlob, {
      headers: {
        "Content-Type": "audio/mpeg",
        "Content-Disposition": `attachment; filename="${track.title} - ${track.artist_name}.mp3"`,
      },
    })
  } catch (error) {
    console.error("Download track error:", error)
    return NextResponse.json({ error: "Failed to download track" }, { status: 500 })
  }
}

export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const body = await request.json()
    const { userId } = body

    if (!userId) {
      return NextResponse.json({ error: "User ID required" }, { status: 400 })
    }

    // Get track info
    const track = await sql`
      SELECT audio_url FROM tracks WHERE id = ${id}
    `

    if (track.length === 0) {
      return NextResponse.json({ error: "Track not found" }, { status: 404 })
    }

    // Check if already downloaded
    const existing = await sql`
      SELECT id FROM downloaded_tracks WHERE user_id = ${userId} AND track_id = ${id}
    `

    if (existing.length === 0) {
      // Insert new download record
      await sql`
        INSERT INTO downloaded_tracks (id, user_id, track_id, quality, created_at)
        VALUES (gen_random_uuid(), ${userId}, ${id}, 'high', NOW())
      `
    }

    return NextResponse.json({
      success: true,
      downloadUrl: track[0].audio_url,
    })
  } catch (error) {
    console.error("Download track error:", error)
    return NextResponse.json({ error: "Failed to download track" }, { status: 500 })
  }
}
