// app/(app)/users/page.tsx
import UsersHeaderClient from './UsersHeaderClient';
import UsersTablesClient from './UsersTablesClient';
import { prisma } from '@/lib/prisma';
import type { User, UserGroup } from '@/generated/prisma/client';

export const dynamic = 'force-dynamic';

type GroupWithUsers = UserGroup & { users: User[] };

export default async function UsersPage() {
  const allGroups = await prisma.userGroup.findMany({
    select: { id: true, name: true },
    orderBy: { name: 'asc' },
  });

  const groups = await prisma.userGroup.findMany({
    orderBy: { name: 'asc' },
    include: {
      users: {
        orderBy: [{ lastName: 'asc' }, { firstName: 'asc' }],
      },
    },
  });

  const ungrouped = await prisma.user.findMany({
    where: { groupId: null },
    orderBy: [{ lastName: 'asc' }, { firstName: 'asc' }],
  });

  return (
    <div className="space-y-6">
      <UsersHeaderClient groups={allGroups} />

      <UsersTablesClient
        groups={groups as GroupWithUsers[]}
        ungrouped={ungrouped}
        allGroups={allGroups}
      />
    </div>
  );
}
