import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";

export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const q = searchParams.get("q") || "";
  const page = Math.max(1, parseInt(searchParams.get("page") || "1", 10));
  const pageSize = Math.min(100, Math.max(1, parseInt(searchParams.get("pageSize") || "20", 10)));
  const where = q
    ? {
        OR: [
          { nickname: { contains: q } },
          { phone: { contains: q } },
          { name: { contains: q } },
        ],
      }
    : {};

  const [total, users] = await Promise.all([
    prisma.user.count({ where }),
    prisma.user.findMany({
      where,
      orderBy: { createdAt: "desc" },
      skip: (page - 1) * pageSize,
      take: pageSize,
      select: {
        userId: true,
        nickname: true,
        name: true,
        phone: true,
        status: true,
        authLevel: true,
        createdAt: true,
        points: true,
        level: true,
        grade: true,
        userRoles: { select: { role: { select: { name: true } } } },
      },
    }),
  ]);

  const items = users.map((u) => ({
    ...u,
    roles: u.userRoles.map((r) => r.role.name),
  }));
  return NextResponse.json({ total, page, pageSize, users: items });
}


