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 albums = await sql`
      SELECT al.*, a.name as artist_name, a.avatar_url as artist_avatar, a.is_verified as artist_verified
      FROM albums al
      LEFT JOIN artists a ON al.artist_id = a.id
      WHERE al.id = ${id}
    `

    if (albums.length === 0) {
      return NextResponse.json({ error: "Album non trouvé" }, { status: 404 })
    }

    // Get album tracks
    const tracks = await sql`
      SELECT * FROM tracks 
      WHERE album_id = ${id}
      ORDER BY disc_number, track_number
    `

    return NextResponse.json({
      ...albums[0],
      tracks,
    })
  } catch (error) {
    console.error("Get album error:", error)
    return NextResponse.json({ error: "Erreur lors de la récupération de l'album" }, { status: 500 })
  }
}

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

    const allowedFields = [
      "title",
      "cover_url",
      "release_date",
      "album_type",
      "label",
      "copyright",
      "is_explicit",
      "status",
    ]

    const setStatements: string[] = []
    for (const [key, value] of Object.entries(updates)) {
      if (allowedFields.includes(key)) {
        if (value === null) {
          setStatements.push(`${key} = NULL`)
        } else if (typeof value === "string") {
          setStatements.push(`${key} = '${value}'`)
        } else if (typeof value === "boolean") {
          setStatements.push(`${key} = ${value}`)
        }
      }
    }

    if (setStatements.length === 0) {
      return NextResponse.json({ error: "Aucun champ valide à mettre à jour" }, { status: 400 })
    }

    const result = await sql`
      UPDATE albums
      SET ${sql.unsafe(setStatements.join(", "))}, updated_at = CURRENT_TIMESTAMP
      WHERE id = ${id}
      RETURNING *
    `

    if (result.length === 0) {
      return NextResponse.json({ error: "Album non trouvé" }, { status: 404 })
    }

    return NextResponse.json(result[0])
  } catch (error) {
    console.error("Update album error:", error)
    return NextResponse.json({ error: "Erreur lors de la mise à jour" }, { status: 500 })
  }
}

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

    await sql`DELETE FROM albums WHERE id = ${id}`

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