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") || "100"),
    })

    console.log("[v0] GET /api/genres - Fetching with limit:", limit, "offset:", offset)

    const genres = await sql`
      SELECT 
        g.*,
        COALESCE(COUNT(DISTINCT tg.track_id), 0) as track_count
      FROM genres g
      LEFT JOIN track_genres tg ON g.id = tg.genre_id
      GROUP BY g.id
      ORDER BY g.created_at DESC, g.name
      LIMIT ${limit} OFFSET ${offset}
    `

    const countResult = await sql`SELECT COUNT(*) as total FROM genres`
    const total = Number.parseInt(countResult[0].total)

    console.log("[v0] GET /api/genres - Total genres in DB:", total, "Returned:", genres.length)

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

export async function POST(request: NextRequest) {
  try {
    const data = await request.json()
    const { name, slug, description, color, icon_url, is_featured = false } = data

    console.log("[v0] POST /api/genres - Request data:", data)

    if (!name || !slug) {
      console.log("[v0] Validation failed - missing name or slug")
      return NextResponse.json({ error: "Nom et slug requis" }, { status: 400 })
    }

    console.log("[v0] Inserting genre into database:", { name, slug, description, color, icon_url, is_featured })

    const genres = await sql`
      INSERT INTO genres (name, slug, description, color, icon_url, is_featured)
      VALUES (${name}, ${slug}, ${description}, ${color}, ${icon_url}, ${is_featured})
      RETURNING *
    `

    console.log("[v0] Genre created successfully:", genres[0])

    return NextResponse.json(genres[0], { status: 201 })
  } catch (error) {
    console.error("[v0] Create genre error:", error)
    return NextResponse.json({ error: "Erreur lors de la création du genre" }, { status: 500 })
  }
}
