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 { searchParams } = new URL(request.url)
    const currentUserId = searchParams.get("current_user_id")

    if (!playlistId || playlistId === "undefined" || playlistId === "null") {
      return NextResponse.json({ error: "Invalid playlist ID" }, { status: 400 })
    }

    const playlist = await sql`
      SELECT p.*, u.name as creator_name
      FROM playlists p
      LEFT JOIN users u ON p.user_id = u.id
      WHERE p.id = ${playlistId}
    `

    if (playlist.length === 0) {
      return NextResponse.json({ error: "Playlist not found" }, { status: 404 })
    }

    const playlistData = playlist[0]
    if (!playlistData.is_public && playlistData.user_id !== currentUserId) {
      return NextResponse.json({ error: "You don't have permission to view this private playlist" }, { status: 403 })
    }

    const tracks = await sql`
      SELECT t.*, a.name as artist_name, al.cover_url as album_cover, pt.added_at
      FROM playlist_tracks pt
      JOIN tracks t ON pt.track_id = t.id
      LEFT JOIN artists a ON t.artist_id = a.id
      LEFT JOIN albums al ON t.album_id = al.id
      WHERE pt.playlist_id = ${playlistId}
      ORDER BY pt.added_at DESC
    `

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

export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id: playlistId } = await params
    const body = await request.json()
    const { name, description, isPublic, cover_url } = body

    const result = await sql`
      UPDATE playlists
      SET name = COALESCE(${name}, name),
          description = COALESCE(${description}, description),
          cover_url = COALESCE(${cover_url}, cover_url),
          is_public = COALESCE(${isPublic}, is_public),
          updated_at = NOW()
      WHERE id = ${playlistId}
      RETURNING *
    `

    return NextResponse.json({ playlist: result[0] })
  } catch (error) {
    console.error("Update playlist error:", error)
    return NextResponse.json({ error: "Failed to update playlist" }, { status: 500 })
  }
}

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

    await sql`DELETE FROM playlist_tracks WHERE playlist_id = ${playlistId}`
    await sql`DELETE FROM playlists WHERE id = ${playlistId}`

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Delete playlist error:", error)
    return NextResponse.json({ error: "Failed to delete playlist" }, { status: 500 })
  }
}
