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 role = searchParams.get("role")
    const status = searchParams.get("status")

    const whereConditions = []
    if (search) {
      whereConditions.push(`(name ILIKE '%${search}%' OR email ILIKE '%${search}%')`)
    }
    if (role) {
      whereConditions.push(`role = '${role}'`)
    }
    if (status === "active") {
      whereConditions.push(`is_active = TRUE`)
    } else if (status === "inactive") {
      whereConditions.push(`is_active = FALSE`)
    }

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

    const users = await sql`
      SELECT id, email, name, avatar_url, role, subscription_type, 
             is_verified, is_active, country, created_at, last_login_at
      FROM users
      ${sql.unsafe(whereClause)}
      ORDER BY created_at DESC
      LIMIT ${limit} OFFSET ${offset}
    `

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

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