import { cookies } from "next/headers";
import { verifyToken } from "@/lib/auth/jwt";
import { listUsers } from "@/lib/localDb";
import UsersClient from "./UsersClient";

export const dynamic = "force-dynamic";

async function getUsers() {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get("auth_token")?.value;
    if (!token) return [];
    const payload = await verifyToken(token);
    if (!payload || payload.role !== "admin") return [];
    return await listUsers();
  } catch {
    return [];
  }
}

export default async function UsersPage() {
  const users = await getUsers();
  return <UsersClient initialUsers={users} />;
}
