import { sql, getPaginationValues } from "@/lib/db"
import { type NextRequest, NextResponse } from "next/server"

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const { page, limit, offset } = getPaginationValues({
      page: Number.parseInt(searchParams.get("page") || "1"),
      limit: Number.parseInt(searchParams.get("limit") || "20"),
    })
    const search = searchParams.get("search") || ""
    const verified = searchParams.get("verified")

    const whereConditions = []
    if (search) {
      whereConditions.push(`a.name ILIKE '%${search}%'`)
    }
    if (verified === "true") {
      whereConditions.push(`a.is_verified = TRUE`)
    } else if (verified === "false") {
      whereConditions.push(`a.is_verified = FALSE`)
    }

    const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(" AND ")}` : ""

    const artists = await sql`
      SELECT 
        a.*,
        (SELECT COUNT(*) FROM tracks t WHERE t.artist_id = a.id) as track_count,
        (SELECT COUNT(*) FROM albums al WHERE al.artist_id = a.id) as album_count,
        (SELECT COALESCE(SUM(t.total_streams), 0) FROM tracks t WHERE t.artist_id = a.id) as total_streams,
        (SELECT COUNT(*) FROM artist_followers af WHERE af.artist_id = a.id) as follower_count
      FROM artists a
      ${sql.unsafe(whereClause)}
      ORDER BY a.monthly_listeners DESC
      LIMIT ${limit} OFFSET ${offset}
    `

    const countResult = await sql`
      SELECT COUNT(*) as total FROM artists a ${sql.unsafe(whereClause)}
    `
    const total = Number.parseInt(countResult[0].total)

    return NextResponse.json({
      data: artists,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    })
  } catch (error) {
    console.error("Get artists error:", error)
    return NextResponse.json({ error: "Erreur lors de la récupération des artistes" }, { status: 500 })
  }
}

export async function POST(request: NextRequest) {
  try {
    const data = await request.json()

    const { user_id, name, bio, avatar_url, cover_url, country, genres } = data

    if (!name) {
      return NextResponse.json({ error: "Le nom est requis" }, { status: 400 })
    }

    const artists = await sql`
      INSERT INTO artists (user_id, name, bio, avatar_url, cover_url, country, genres)
      VALUES (${user_id}, ${name}, ${bio}, ${avatar_url}, ${cover_url}, ${country}, ${genres || []})
      RETURNING *
    `

    return NextResponse.json(artists[0], { status: 201 })
  } catch (error) {
    console.error("Create artist error:", error)
    return NextResponse.json({ error: "Erreur lors de la création de l'artiste" }, { status: 500 })
  }
}
