import { NextResponse } from "next/server"
import { getAdminSession } from "@/lib/session"
import { getUsersPage } from "@/lib/db/admin-queries"

export async function GET(request: Request) {
  const admin = await getAdminSession()
  if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 })

  const { searchParams } = new URL(request.url)

  const result = await getUsersPage({
    q: searchParams.get("q") ?? undefined,
    page: Number(searchParams.get("page")) || 1,
    pageSize: Math.min(100, Number(searchParams.get("pageSize")) || 25),
    plan: searchParams.get("plan") ?? undefined,
    sort: searchParams.get("sort") ?? undefined,
    dir: (searchParams.get("dir") as "asc" | "desc") ?? undefined,
  })

  return NextResponse.json(result)
}
