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

/** Every login credential on the platform (passwordHash is never selected). */
export async function GET() {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const accounts = await prisma.user.findMany({
    orderBy: [{ role: "desc" }, { createdAt: "asc" }],
    select: {
      id: true,
      name: true,
      email: true,
      username: true,
      role: true,
      institutionId: true,
      createdAt: true,
      institution: {
        select: {
          name: true,
          type: true,
          status: true,
          parent: { select: { name: true } },
        },
      },
    },
  });

  return NextResponse.json({
    accounts: accounts.map(({ institution, ...account }) => ({
      ...account,
      institution: institution
        ? {
            name: institution.name,
            type: institution.type,
            status: institution.status,
            parentName: institution.parent?.name ?? null,
          }
        : null,
    })),
  });
}
