import { redirect } from "next/navigation";
import UsersPageClient from "@/components/users/UsersPageClient";
import { getCurrentUser } from "@/lib/currentUser";
import { listManagedAccounts } from "@/lib/userManagement";
import { shopRepository } from "@/lib/repositories/shopRepository";

export const dynamic = "force-dynamic";

export default async function UsersPage() {
  const current = await getCurrentUser();
  if (!current) redirect("/login");
  if (current.role === "staff") redirect("/dashboard");
  const [rows, shops] = await Promise.all([
    listManagedAccounts({ id: current.id, role: current.role }),
    current.role === "super_admin" ? shopRepository.findScopeOptions() : Promise.resolve([]),
  ]);
  return <UsersPageClient currentRole={current.role} shops={shops} rows={(rows || []).map((row) => ({ ...row, passwordSetAt: row.passwordSetAt?.toISOString() ?? null, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }))} />;
}
