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 AdminPage() {
  const current = await getCurrentUser();
  if (!current) redirect("/login");
  if (current.role !== "super_admin") redirect("/dashboard?shop_id=all");

  const [rows, shops] = await Promise.all([
    listManagedAccounts({ id: current.id, role: current.role }),
    shopRepository.findScopeOptions(),
  ]);
  return <UsersPageClient currentRole="super_admin" dashboard shops={shops} rows={(rows || []).map((row) => ({
    ...row,
    passwordSetAt: row.passwordSetAt?.toISOString() ?? null,
    createdAt: row.createdAt.toISOString(),
    updatedAt: row.updatedAt.toISOString(),
  }))} />;
}
