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

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams
    const query = searchParams.get("q")

    if (!query) {
      return NextResponse.json({ artists: [], tracks: [], albums: [], playlists: [] })
    }

    const searchTerm = `%${query}%`

    // Search artists
    const artists = await sql`
      SELECT id, name, avatar_url, cover_url, total_followers, is_verified
      FROM artists
      WHERE name ILIKE ${searchTerm}
      LIMIT 10
    `

    // Search tracks with artist name
    const tracks = await sql`
      SELECT t.*, a.name as artist_name
      FROM tracks t
      LEFT JOIN artists a ON t.artist_id = a.id
      WHERE t.title ILIKE ${searchTerm}
        AND t.status = 'published'
      LIMIT 20
    `

    // Search albums with artist name
    const albums = await sql`
      SELECT al.*, a.name as artist_name
      FROM albums al
      LEFT JOIN artists a ON al.artist_id = a.id
      WHERE al.title ILIKE ${searchTerm}
        AND al.status = 'published'
      LIMIT 10
    `

    // Search playlists
    const playlists = await sql`
      SELECT *
      FROM playlists
      WHERE name ILIKE ${searchTerm}
        AND is_public = true
      LIMIT 10
    `

    return NextResponse.json({
      artists,
      tracks,
      albums,
      playlists,
    })
  } catch (error) {
    console.error("Search error:", error)
    return NextResponse.json({ error: "Erreur lors de la recherche" }, { status: 500 })
  }
}
