import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getDepartmentLabel } from "@/lib/departments";
import { ROLE_LABELS } from "@/lib/utils";
import { resolveHighestUserRole } from "@/lib/role-resolution";
import type { DepartmentKey, UserRole } from "@/lib/types";

type PersonRecord = {
  id: string;
  name: string;
  email: string;
  role: UserRole;
  roleLabel: string;
  department: DepartmentKey | null;
  departmentLabel: string | null;
  departmentRole: string | null;
  status: string;
};

export async function GET() {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const users = await prisma.user.findMany({
    select: {
      id: true,
      name: true,
      email: true,
      status: true,
      department: true,
      departmentRole: true,
      userRoles: {
        include: {
          role: true,
        },
        orderBy: { assignedAt: "asc" },
      },
    },
    orderBy: [{ name: "asc" }, { email: "asc" }],
  });

  const people: PersonRecord[] = users.map((user) => {
    const resolvedRole = resolveHighestUserRole(user.userRoles.map((entry) => entry.role.key));
    const roleLabel = ROLE_LABELS[resolvedRole];
    const department = user.department ?? null;

    return {
      id: user.id,
      name: user.name?.trim() || user.email,
      email: user.email,
      role: resolvedRole,
      roleLabel,
      department,
      departmentLabel: department ? getDepartmentLabel(department) : null,
      departmentRole: user.departmentRole ?? null,
      status: user.status,
    };
  });

  return NextResponse.json({ ok: true, people });
}
