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 userId = searchParams.get("userId")

    // Get total like count
    const countResult = await sql`
      SELECT COUNT(*) as count FROM liked_tracks WHERE track_id = ${id}
    `

    let isLiked = false
    if (userId) {
      const likedResult = await sql`
        SELECT 1 FROM liked_tracks WHERE track_id = ${id} AND user_id = ${userId}
      `
      isLiked = likedResult.length > 0
    }

    return NextResponse.json({
      count: Number.parseInt(countResult[0]?.count || "0"),
      isLiked,
    })
  } catch (error) {
    console.error("Get track likes error:", error)
    return NextResponse.json({ count: 0, isLiked: false })
  }
}

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

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

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

    if (existing.length > 0) {
      return NextResponse.json({ message: "Déjà aimé" })
    }

    await sql`
      INSERT INTO liked_tracks (id, track_id, user_id)
      VALUES (gen_random_uuid(), ${id}, ${userId})
    `

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Like track error:", error)
    return NextResponse.json({ error: "Erreur lors du like" }, { status: 500 })
  }
}

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

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

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

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Unlike track error:", error)
    return NextResponse.json({ error: "Erreur lors du unlike" }, { status: 500 })
  }
}
