import { safeQuery } from "@/lib/db"
import { successResponse, errorResponse } from "@/lib/api-response"

export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id: userId } = await params

    if (!process.env.DATABASE_URL && !process.env.POSTGRES_URL) {
      console.error("[v0] DATABASE_URL/POSTGRES_URL not configured")
      return errorResponse("Database not configured", 500)
    }

    const playlists = await safeQuery<any>`
      SELECT 
        p.id,
        p.name,
        p.description,
        p.cover_url,
        p.is_public,
        p.total_tracks,
        p.total_duration_ms,
        p.created_at,
        p.updated_at
      FROM playlists p
      WHERE p.user_id = ${userId}
      ORDER BY p.updated_at DESC
    `

    console.log("[v0] Found playlists:", playlists.length)

    return successResponse({
      playlists,
      total: playlists.length,
    })
  } catch (error: any) {
    console.error("[API] Get user playlists error:", error)
    console.error("[v0] Error details:", {
      message: error?.message,
      code: error?.code,
      status: error?.status,
    })

    if (error?.message?.includes("Too Many") || error?.status === 429) {
      return errorResponse("Rate limit exceeded", 429)
    }

    return errorResponse(error?.message || "Failed to get playlists", 500)
  }
}
