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

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

  if (!token || !apiKey) {
    return NextResponse.json({ error: "Missing token or API key", code: "AUTH_REQUIRED" }, { status: 401 })
  }

  try {
    // Verify API key
    const apiKeyResult = await sql`
      SELECT id, status FROM external_api_keys
      WHERE api_key = ${apiKey} AND status = 'active'
    `

    if (apiKeyResult.length === 0) {
      return NextResponse.json({ error: "Invalid API key", code: "INVALID_KEY" }, { status: 401 })
    }

    // Decode and verify token
    const decoded = Buffer.from(token, "base64").toString()
    const [downloadId, timestamp] = decoded.split(":")

    // Check if token is expired (1 hour)
    const tokenAge = Date.now() - Number.parseInt(timestamp)
    if (tokenAge > 3600000) {
      return NextResponse.json({ error: "Download link expired", code: "EXPIRED" }, { status: 410 })
    }

    // Verify download record exists and belongs to this API key
    const downloadResult = await sql`
      SELECT rd.id, rd.track_id, rd.delivery_status, t.audio_url, t.title
      FROM ringtone_downloads rd
      JOIN tracks t ON rd.track_id = t.id
      WHERE rd.id = ${downloadId}
      AND rd.api_key_id = ${apiKeyResult[0].id}
    `

    if (downloadResult.length === 0) {
      return NextResponse.json({ error: "Download not found", code: "NOT_FOUND" }, { status: 404 })
    }

    const download = downloadResult[0]
    const audioUrl = download.audio_url

    if (!audioUrl) {
      return NextResponse.json({ error: "Audio file not available", code: "FILE_NOT_FOUND" }, { status: 404 })
    }

    // Update delivery status
    await sql`
      UPDATE ringtone_downloads
      SET delivery_status = 'delivered',
          delivered_at = NOW(),
          updated_at = NOW()
      WHERE id = ${downloadId}
    `

    // Fetch the audio file and stream it
    let fileUrl = audioUrl

    // Handle R2 URLs - route through proxy
    if (audioUrl.includes("afrique-musique.com") || audioUrl.includes("africa-music")) {
      const path = audioUrl.split("/").slice(-2).join("/")
      fileUrl = `${process.env.NEXT_PUBLIC_APP_URL || ""}/api/proxy-media/${path}`
    }

    // For Vercel Blob URLs, use directly
    if (audioUrl.includes("blob.vercel-storage.com")) {
      fileUrl = audioUrl
    }

    // Redirect to the file URL for download
    return NextResponse.redirect(fileUrl)
  } catch (error) {
    console.error("Error processing download:", error)
    return NextResponse.json({ error: "Internal server error", code: "SERVER_ERROR" }, { status: 500 })
  }
}
