import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { redirect } from "next/navigation";
import { UsersTable } from "./users-table";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "User Management" };

export default async function AdminUsersPage() {
  const session = await auth();
  if (!session?.user) redirect("/login");

  if (!hasPermission(session.user.role, "manage_users")) redirect("/dashboard");

  const users = await db.user.findMany({ orderBy: { createdAt: "desc" } });

  return (
    <UsersTable
      users={users.map((u) => ({
        id: u.id,
        employeeId: u.employeeId,
        name: u.name,
        email: u.email,
        role: u.role,
        isActive: u.isActive,
        createdAt: u.createdAt.toISOString(),
      }))}
    />
  );
}
