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 artistResult = await sql`
      SELECT 
        a.*,
        COALESCE((SELECT COUNT(*) FROM tracks WHERE artist_id = a.id AND status = 'published'), 0) as track_count,
        COALESCE((SELECT COUNT(*) FROM albums WHERE artist_id = a.id AND status = 'published'), 0) as album_count,
        COALESCE((SELECT COUNT(*) FROM artist_followers WHERE artist_id = a.id), 0) as follower_count
      FROM artists a
      WHERE a.id = ${id}
    `

    if (artistResult.length === 0) {
      return NextResponse.json({ error: "Artiste non trouve" }, { status: 404 })
    }

    const tracksResult = await sql`
      SELECT 
        t.id,
        t.title,
        t.cover_url,
        t.audio_url,
        t.duration_ms,
        t.play_count,
        t.created_at
      FROM tracks t
      WHERE t.artist_id = ${id} AND t.status = 'published'
      ORDER BY t.play_count DESC, t.created_at DESC
      LIMIT 20
    `

    const artist = {
      ...artistResult[0],
      track_count: Number(artistResult[0].track_count),
      album_count: Number(artistResult[0].album_count),
      follower_count: Number(artistResult[0].follower_count),
      tracks: tracksResult, // Include tracks in response
    }

    return NextResponse.json({ data: artist })
  } catch (error) {
    console.error("Get artist error:", error)
    return NextResponse.json({ error: "Erreur lors de la recuperation de l'artiste" }, { 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] Artist PATCH request - ID:", id)
    console.log("[v0] Update payload:", JSON.stringify(updates, null, 2))

    const allowedFields = ["name", "bio", "avatar_url", "cover_url", "is_verified", "country", "social_links", "genres"]

    const updateValues: Record<string, any> = {}

    for (const [key, value] of Object.entries(updates)) {
      if (allowedFields.includes(key)) {
        updateValues[key] = value
      }
    }

    if (Object.keys(updateValues).length === 0) {
      console.log("[v0] No valid fields to update")
      return NextResponse.json({ error: "Aucun champ valide a mettre a jour" }, { status: 400 })
    }

    console.log("[v0] Filtered update values:", JSON.stringify(updateValues, null, 2))

    let result

    // Handle different update scenarios using tagged template literals
    if (updateValues.avatar_url !== undefined && Object.keys(updateValues).length === 1) {
      // Only avatar_url update
      result = await sql`
        UPDATE artists
        SET avatar_url = ${updateValues.avatar_url}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else if (updateValues.cover_url !== undefined && Object.keys(updateValues).length === 1) {
      // Only cover_url update
      result = await sql`
        UPDATE artists
        SET cover_url = ${updateValues.cover_url}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else {
      // Full profile update with all fields
      const name = updateValues.name ?? null
      const bio = updateValues.bio ?? null
      const country = updateValues.country ?? null
      const genres = updateValues.genres ?? null
      const socialLinks = updateValues.social_links ? JSON.stringify(updateValues.social_links) : null
      const avatarUrl = updateValues.avatar_url ?? null
      const coverUrl = updateValues.cover_url ?? null
      const isVerified = updateValues.is_verified ?? null

      console.log("[v0] Executing full profile update with values:", {
        name,
        bio,
        country,
        genres,
        socialLinks,
        avatarUrl,
        coverUrl,
        isVerified,
      })

      result = await sql`
        UPDATE artists
        SET 
          name = COALESCE(${name}, name),
          bio = COALESCE(${bio}, bio),
          country = COALESCE(${country}, country),
          genres = COALESCE(${genres}::text[], genres),
          social_links = COALESCE(${socialLinks}::jsonb, social_links),
          avatar_url = COALESCE(${avatarUrl}, avatar_url),
          cover_url = COALESCE(${coverUrl}, cover_url),
          is_verified = COALESCE(${isVerified}, is_verified),
          updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    }

    console.log("[v0] Update result:", result?.length ? "Success" : "No rows returned")

    if (!result || result.length === 0) {
      return NextResponse.json({ error: "Artiste non trouve" }, { status: 404 })
    }

    // Return consistent format with data wrapper
    return NextResponse.json({ data: result[0], success: true })
  } catch (error) {
    console.error("[v0] Update artist error:", error)
    return NextResponse.json({ error: "Erreur lors de la mise a jour" }, { status: 500 })
  }
}

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

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

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