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

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

    const tracks = await sql`
      SELECT 
        t.id,
        t.title,
        t.audio_url,
        t.cover_url,
        t.duration_ms,
        t.total_streams as plays_count,
        a.name as artist_name,
        a.id as artist_id,
        pt.added_at,
        pt.position
      FROM playlist_tracks pt
      JOIN tracks t ON pt.track_id = t.id
      LEFT JOIN artists a ON t.artist_id = a.id
      WHERE pt.playlist_id = ${playlistId}
      ORDER BY pt.position ASC, pt.added_at DESC
    `

    return NextResponse.json({ tracks })
  } catch (error) {
    console.error("Get playlist tracks error:", error)
    return NextResponse.json({ error: "Failed to fetch tracks" }, { status: 500 })
  }
}

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

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

    // Check if playlist exists
    const playlistExists = await sql`SELECT id FROM playlists WHERE id = ${playlistId}`
    if (playlistExists.length === 0) {
      return NextResponse.json({ error: "Playlist not found" }, { status: 404 })
    }

    // Check if track exists
    const trackExists = await sql`SELECT id FROM tracks WHERE id = ${trackId}`
    if (trackExists.length === 0) {
      return NextResponse.json({ error: "Track not found" }, { status: 404 })
    }

    // Check if already in playlist
    const existing = await sql`
      SELECT id FROM playlist_tracks 
      WHERE playlist_id = ${playlistId} AND track_id = ${trackId}
    `

    if (existing.length > 0) {
      return NextResponse.json({ success: true, message: "Track already in playlist" })
    }

    // Get next position
    const maxPos = await sql`
      SELECT COALESCE(MAX(position), 0) + 1 as next_pos 
      FROM playlist_tracks 
      WHERE playlist_id = ${playlistId}
    `
    const nextPosition = maxPos[0]?.next_pos || 1

    // Insert the track
    const result = await sql`
      INSERT INTO playlist_tracks (id, playlist_id, track_id, position, added_at)
      VALUES (gen_random_uuid(), ${playlistId}, ${trackId}, ${nextPosition}, NOW())
      RETURNING *
    `

    if (result.length === 0) {
      return NextResponse.json({ error: "Failed to insert track" }, { status: 500 })
    }

    return NextResponse.json({ success: true, playlistTrack: result[0] })
  } catch (error) {
    console.error("Add track to playlist error:", error)
    return NextResponse.json({ error: "Failed to add track" }, { status: 500 })
  }
}

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

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

    await sql`
      DELETE FROM playlist_tracks
      WHERE playlist_id = ${playlistId} AND track_id = ${trackId}
    `

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Remove track from playlist error:", error)
    return NextResponse.json({ error: "Failed to remove track" }, { status: 500 })
  }
}
