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 history = await sql`
      SELECT t.*, a.name as artist_name, lh.played_at
      FROM listening_history lh
      JOIN tracks t ON lh.track_id = t.id
      LEFT JOIN artists a ON t.artist_id = a.id
      WHERE lh.user_id = ${id}
      ORDER BY lh.played_at DESC
      LIMIT 100
    `

    return NextResponse.json({ data: history })
  } catch (error) {
    console.error("Get history error:", error)
    return NextResponse.json({ error: "Erreur lors de la recuperation" }, { status: 500 })
  }
}

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

    if (!trackId) {
      return NextResponse.json({ error: "Track ID is required" }, { status: 400 })
    }

    await sql`
      INSERT INTO listening_history (id, user_id, track_id, played_at)
      VALUES (gen_random_uuid(), ${id}, ${trackId}, NOW())
    `

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Add to history error:", error)
    return NextResponse.json({ error: "Erreur lors de l'ajout" }, { status: 500 })
  }
}

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

    await sql`
      DELETE FROM listening_history WHERE user_id = ${id}
    `

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Clear history error:", error)
    return NextResponse.json({ error: "Erreur lors de la suppression" }, { status: 500 })
  }
}
