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

    if (!id || id.length < 36) {
      return NextResponse.json({ error: "ID de piste invalide" }, { status: 400 })
    }

    const tracks = await sql`
      SELECT t.*, 
             a.name as artist_name, a.avatar_url as artist_avatar, a.is_verified as artist_verified,
             al.title as album_title, al.cover_url as album_cover
      FROM tracks t
      LEFT JOIN artists a ON t.artist_id = a.id
      LEFT JOIN albums al ON t.album_id = al.id
      WHERE t.id = ${id}
    `

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

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

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

    console.log("[v0] [Track Update] Updating track:", id, "with data:", updates)

    if (!id || id.length < 36) {
      return NextResponse.json({ error: "ID de piste invalide" }, { status: 400 })
    }

    if (!updates || Object.keys(updates).length === 0) {
      return NextResponse.json({ error: "Aucune mise à jour fournie" }, { status: 400 })
    }

    const allowedFields = [
      "title",
      "album_id",
      "cover_url",
      "track_number",
      "is_explicit",
      "lyrics",
      "status",
      "is_playable",
      "rejection_reason",
      "duration_ms",
    ]

    const validStatuses = ["draft", "pending", "published", "archived", "rejected"]

    // Validate and collect updates
    const validUpdates: Record<string, any> = {}

    for (const [key, value] of Object.entries(updates)) {
      if (allowedFields.includes(key)) {
        // Validate field-specific constraints
        if (key === "title" && typeof value === "string" && value.length > 255) {
          return NextResponse.json({ error: "Le titre est trop long (max 255 caractères)" }, { status: 400 })
        }
        if (key === "duration_ms" && typeof value === "number" && (value < 0 || value > 3600000)) {
          return NextResponse.json({ error: "Durée invalide" }, { status: 400 })
        }
        if (key === "status" && !validStatuses.includes(value as string)) {
          return NextResponse.json({ error: `Statut invalide. Valeurs autorisées: ${validStatuses.join(", ")}` }, { status: 400 })
        }

        validUpdates[key] = value
      }
    }

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

    // Build update query dynamically but safely
    let result
    
    // Handle different update scenarios
    if (validUpdates.status !== undefined && Object.keys(validUpdates).length === 1) {
      // Only status update
      result = await sql`
        UPDATE tracks
        SET status = ${validUpdates.status}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else if (validUpdates.title !== undefined && validUpdates.status !== undefined) {
      // Title and status
      result = await sql`
        UPDATE tracks
        SET title = ${validUpdates.title}, status = ${validUpdates.status}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else if (validUpdates.title !== undefined) {
      // Only title
      result = await sql`
        UPDATE tracks
        SET title = ${validUpdates.title}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else if (validUpdates.is_playable !== undefined) {
      // Playable status
      result = await sql`
        UPDATE tracks
        SET is_playable = ${validUpdates.is_playable}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else if (validUpdates.rejection_reason !== undefined) {
      // Rejection with reason
      result = await sql`
        UPDATE tracks
        SET status = 'rejected', rejection_reason = ${validUpdates.rejection_reason}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else if (validUpdates.lyrics !== undefined) {
      // Lyrics update
      result = await sql`
        UPDATE tracks
        SET lyrics = ${validUpdates.lyrics}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else if (validUpdates.cover_url !== undefined) {
      // Cover URL update
      result = await sql`
        UPDATE tracks
        SET cover_url = ${validUpdates.cover_url}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else {
      // Generic update for other fields - update one by one
      for (const [key, value] of Object.entries(validUpdates)) {
        if (key === "album_id") {
          await sql`UPDATE tracks SET album_id = ${value} WHERE id = ${id}`
        } else if (key === "track_number") {
          await sql`UPDATE tracks SET track_number = ${value} WHERE id = ${id}`
        } else if (key === "is_explicit") {
          await sql`UPDATE tracks SET is_explicit = ${value} WHERE id = ${id}`
        } else if (key === "duration_ms") {
          await sql`UPDATE tracks SET duration_ms = ${value} WHERE id = ${id}`
        }
      }
      // Fetch the updated record
      result = await sql`SELECT * FROM tracks WHERE id = ${id}`
    }

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

    console.log("[v0] [Track Update] Update successful:", result[0].id)
    return NextResponse.json(result[0])
  } catch (error: any) {
    console.error("[v0] Update track error:", error)
    return NextResponse.json(
      {
        error: "Erreur lors de la mise à jour",
        details: process.env.NODE_ENV === "development" ? error.message : undefined,
      },
      { status: 500 },
    )
  }
}

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

    if (!id || id.length < 36) {
      return NextResponse.json({ error: "ID de piste invalide" }, { status: 400 })
    }

    const result = await sql`DELETE FROM tracks WHERE id = ${id} RETURNING id`

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

    console.log("[v0] Track deleted:", id)
    return NextResponse.json({ success: true, id: result[0].id })
  } catch (error) {
    console.error("[v0] Delete track error:", error)
    return NextResponse.json({ error: "Erreur lors de la suppression" }, { status: 500 })
  }
}
