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

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

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

    await sql`
      INSERT INTO liked_tracks (user_id, track_id, liked_at)
      VALUES (${userId}, ${trackId}, NOW())
      ON CONFLICT (user_id, track_id) DO NOTHING
    `

    return NextResponse.json({ success: true, liked: true })
  } catch (error) {
    console.error("Like track error:", error)
    return NextResponse.json({ error: "Failed to like track" }, { status: 500 })
  }
}

export async function DELETE(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id: trackId } = await params
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get("userId")

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

    await sql`
      DELETE FROM liked_tracks
      WHERE user_id = ${userId} AND track_id = ${trackId}
    `

    return NextResponse.json({ success: true, liked: false })
  } catch (error) {
    console.error("Unlike track error:", error)
    return NextResponse.json({ error: "Failed to unlike track" }, { status: 500 })
  }
}
