import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { requireApiAuthWithOrg, handleApiError } from "@/lib/api-auth";

export async function GET(req: NextRequest) {
  try {
    const session = await requireApiAuthWithOrg();
    const role = req.nextUrl.searchParams.get("role") || undefined;

    const where: Record<string, unknown> = {
      organizationId: session.user.orgId,
    };
    if (role) where.user = { role };

    const members = await prisma.orgMember.findMany({
      where,
      include: {
        user: {
          select: {
            id: true,
            username: true,
            displayName: true,
            email: true,
            avatarUrl: true,
            role: true,
          },
        },
      },
      orderBy: { user: { displayName: "asc" } },
    });

    const users = members.map((m) => m.user);

    return NextResponse.json({ users });
  } catch (error) {
    return handleApiError(error);
  }
}
